utils.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. function padZero(num, targetLength = 2) {
  2. let str = num + '';
  3. while (str.length < targetLength) {
  4. str = '0' + str;
  5. }
  6. return str;
  7. }
  8. const SECOND = 1000;
  9. const MINUTE = 60 * SECOND;
  10. const HOUR = 60 * MINUTE;
  11. const DAY = 24 * HOUR;
  12. export function parseTimeData(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. days,
  20. hours,
  21. minutes,
  22. seconds,
  23. milliseconds,
  24. };
  25. }
  26. export function parseFormat(format, timeData) {
  27. const { days } = timeData;
  28. let { hours, minutes, seconds, milliseconds } = timeData;
  29. if (format.indexOf('DD') === -1) {
  30. hours += days * 24;
  31. } else {
  32. format = format.replace('DD', padZero(days));
  33. }
  34. if (format.indexOf('HH') === -1) {
  35. minutes += hours * 60;
  36. } else {
  37. format = format.replace('HH', padZero(hours));
  38. }
  39. if (format.indexOf('mm') === -1) {
  40. seconds += minutes * 60;
  41. } else {
  42. format = format.replace('mm', padZero(minutes));
  43. }
  44. if (format.indexOf('ss') === -1) {
  45. milliseconds += seconds * 1000;
  46. } else {
  47. format = format.replace('ss', padZero(seconds));
  48. }
  49. return format.replace('SSS', padZero(milliseconds, 3));
  50. }
  51. export function isSameSecond(time1, time2) {
  52. return Math.floor(time1 / 1000) === Math.floor(time2 / 1000);
  53. }