utils.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. export const TimeDataUnit = {
  2. DD: '天',
  3. HH: '时',
  4. mm: '分',
  5. ss: '秒',
  6. SSS: '毫秒',
  7. };
  8. const SECOND = 1000;
  9. const MINUTE = 60 * SECOND;
  10. const HOUR = 60 * MINUTE;
  11. const DAY = 24 * HOUR;
  12. export const parseTimeData = function (time) {
  13. const days = Math.floor(time / DAY);
  14. const hours = Math.floor((time % DAY) / HOUR);
  15. const minutes = Math.floor((time % HOUR) / MINUTE);
  16. const seconds = Math.floor((time % MINUTE) / SECOND);
  17. const milliseconds = Math.floor(time % SECOND);
  18. return {
  19. DD: days,
  20. HH: hours,
  21. mm: minutes,
  22. ss: seconds,
  23. SSS: milliseconds,
  24. };
  25. };
  26. export const isSameSecond = function (time1, time2) {
  27. return Math.floor(time1 / 1000) === Math.floor(time2 / 1000);
  28. };
  29. export const parseFormat = function (time, format) {
  30. const obj = {
  31. 'D+': Math.floor(time / 86400000),
  32. 'H+': Math.floor((time % 86400000) / 3600000),
  33. 'm+': Math.floor((time % 3600000) / 60000),
  34. 's+': Math.floor((time % 60000) / 1000),
  35. 'S+': Math.floor(time % 1000),
  36. };
  37. const timeList = [];
  38. let timeText = format;
  39. Object.keys(obj).forEach((prop) => {
  40. if (new RegExp(`(${prop})`).test(timeText)) {
  41. timeText = timeText.replace(RegExp.$1, (match, offset, source) => {
  42. const v = `${obj[prop]}`;
  43. let digit = v;
  44. if (match.length > 1) {
  45. digit = (match.replace(new RegExp(match[0], 'g'), '0') + v).substr(v.length);
  46. }
  47. const unit = source.substr(offset + match.length);
  48. const last = timeList[timeList.length - 1];
  49. if (last) {
  50. const index = last.unit.indexOf(match);
  51. if (index !== -1) {
  52. last.unit = last.unit.substr(0, index);
  53. }
  54. }
  55. timeList.push({ digit, unit, match });
  56. return digit;
  57. });
  58. }
  59. });
  60. return { timeText, timeList };
  61. };