utils.js 1.9 KB

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