utils.js 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. }
  32. else {
  33. format = format.replace('DD', padZero(days));
  34. }
  35. if (format.indexOf('HH') === -1) {
  36. minutes += hours * 60;
  37. }
  38. else {
  39. format = format.replace('HH', padZero(hours));
  40. }
  41. if (format.indexOf('mm') === -1) {
  42. seconds += minutes * 60;
  43. }
  44. else {
  45. format = format.replace('mm', padZero(minutes));
  46. }
  47. if (format.indexOf('ss') === -1) {
  48. milliseconds += seconds * 1000;
  49. }
  50. else {
  51. format = format.replace('ss', padZero(seconds));
  52. }
  53. return format.replace('SSS', padZero(milliseconds, 3));
  54. }
  55. export function isSameSecond(time1, time2) {
  56. return Math.floor(time1 / 1000) === Math.floor(time2 / 1000);
  57. }