utils.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. /**
  23. *
  24. * @param time 倒计时时间,毫秒单位
  25. * @param format 倒计时格式化字符串,例如:dd天hh小时mm分ss秒SSS毫秒,hh:mm:ss.SSS,hh:mm:ss
  26. */
  27. export const parseFormat = function (time, format) {
  28. const obj = {
  29. 'D+': Math.floor(time / 86400000),
  30. 'H+': Math.floor((time % 86400000) / 3600000),
  31. 'm+': Math.floor((time % 3600000) / 60000),
  32. 's+': Math.floor((time % 60000) / 1000),
  33. 'S+': Math.floor(time % 1000), // 毫秒
  34. };
  35. const timeList = [];
  36. let timeText = format;
  37. Object.keys(obj).forEach((prop) => {
  38. if (new RegExp(`(${prop})`).test(timeText)) {
  39. timeText = timeText.replace(RegExp.$1, (match, offset, source) => {
  40. const v = `${obj[prop]}`;
  41. let digit = v;
  42. if (match.length > 1) {
  43. digit = (match.replace(new RegExp(match[0], 'g'), '0') + v).substr(v.length);
  44. }
  45. const unit = source.substr(offset + match.length);
  46. const last = timeList[timeList.length - 1];
  47. if (last) {
  48. const index = last.unit.indexOf(match);
  49. if (index !== -1) {
  50. last.unit = last.unit.substr(0, index);
  51. }
  52. }
  53. timeList.push({ digit, unit, match });
  54. return digit;
  55. });
  56. }
  57. });
  58. return { timeText, timeList };
  59. };
  60. //# sourceMappingURL=utils.js.map