utils.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // 获取任意时间
  2. export const getDate = (date, AddDayCount = 0) => {
  3. if (!date) {
  4. date = new Date();
  5. }
  6. if (typeof date !== 'object') {
  7. date = date.replace(/-/g, '/');
  8. }
  9. const dd = new Date(date);
  10. dd.setDate(dd.getDate() + AddDayCount); // 获取AddDayCount天后的日期
  11. const y = dd.getFullYear();
  12. const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1; // 获取当前月份的日期,不足10补0
  13. const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate(); // 获取当前几号,不足10补0
  14. const dayStrList = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  15. const HMS = `${dd.getHours() < 10 ? '0' + dd.getHours() : dd.getHours()}${dd.getMinutes() < 10 ? '0' + dd.getMinutes() : dd.getMinutes()}${
  16. dd.getSeconds() < 10 ? '0' + dd.getSeconds() : dd.getSeconds()
  17. }`;
  18. return {
  19. fullDate: y + '-' + m + '-' + d,
  20. year: y,
  21. month: m,
  22. date: d,
  23. day: dd.getDay(),
  24. dayStr: dayStrList[dd.getDay()],
  25. rStr: `${m}月${d}日`,
  26. HMS
  27. };
  28. };
  29. // 通用跳转方法
  30. export function go(url, mode = 'navigateTo') {
  31. if (url == -1) {
  32. let pages = getCurrentPages(); //获取页面
  33. let beforePage = pages[pages.length - 2]; //上个页面
  34. if (beforePage) {
  35. uni.navigateBack();
  36. } else {
  37. uni.reLaunch({
  38. url: '/pages/index/index'
  39. });
  40. }
  41. } else {
  42. uni[mode]({
  43. url
  44. });
  45. }
  46. }
  47. export function sToHs(s) {
  48. //计算分钟
  49. //算法:将秒数除以60,然后下舍入,既得到分钟数
  50. let h;
  51. h = Math.floor(s / 60);
  52. //计算秒
  53. //算法:取得秒%60的余数,既得到秒数
  54. s = s % 60;
  55. //将变量转换为字符串
  56. h += '';
  57. s += '';
  58. //如果只有一位数,前面增加一个0
  59. h = h.length === 1 ? '0' + h : h;
  60. s = Math.floor(s * 100) / 100;
  61. s = s.length === 1 ? '0' + s : s;
  62. if (parseInt(s) < 10) s = '0' + s;
  63. return '00:' + h + ':' + s;
  64. }
  65. // 将时间格式'00:00:00.00' 转成毫秒
  66. export function timeToMilliseconds(timeString) {
  67. // 拆分时间字符串
  68. const [hours, minutes, secondsWithMs] = timeString.split(':');
  69. const [seconds, milliseconds] = secondsWithMs.split('.');
  70. // 转换为秒数
  71. const totalMilliseconds =
  72. parseInt(hours) * 3600 * 1000 + // 小时转毫秒
  73. parseInt(minutes) * 60 * 1000 + // 分钟转毫秒
  74. parseFloat(`${seconds}.${milliseconds}`) * 1000; // 秒和毫秒转毫秒
  75. return totalMilliseconds;
  76. }
  77. // 将毫秒转长度
  78. export function getTrackLength(str) {
  79. const milliseconds = timeToMilliseconds(str);
  80. return Math.round(milliseconds / 12.5);
  81. }
  82. export default {
  83. getDate,
  84. go,
  85. sToHs,
  86. timeToMilliseconds,
  87. getTrackLength
  88. };