utils.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // 补0,如1 -> 01
  2. function padZero(num, targetLength = 2) {
  3. let str = `${num}`
  4. while (str.length < targetLength) {
  5. str = `0${str}`
  6. }
  7. return str
  8. }
  9. const SECOND = 1000
  10. const MINUTE = 60 * SECOND
  11. const HOUR = 60 * MINUTE
  12. const DAY = 24 * HOUR
  13. export function parseTimeData(time) {
  14. const days = Math.floor(time / DAY)
  15. const hours = Math.floor((time % DAY) / HOUR)
  16. const minutes = Math.floor((time % HOUR) / MINUTE)
  17. const seconds = Math.floor((time % MINUTE) / SECOND)
  18. const milliseconds = Math.floor(time % SECOND)
  19. return {
  20. days,
  21. hours,
  22. minutes,
  23. seconds,
  24. milliseconds
  25. }
  26. }
  27. export function parseFormat(format, timeData) {
  28. let {
  29. days,
  30. hours,
  31. minutes,
  32. seconds,
  33. milliseconds
  34. } = timeData
  35. // 如果格式化字符串中不存在DD(天),则将天的时间转为小时中去
  36. if (format.indexOf('DD') === -1) {
  37. hours += days * 24
  38. } else {
  39. // 对天补0
  40. format = format.replace('DD', padZero(days))
  41. }
  42. // 其他同理于DD的格式化处理方式
  43. if (format.indexOf('HH') === -1) {
  44. minutes += hours * 60
  45. } else {
  46. format = format.replace('HH', padZero(hours))
  47. }
  48. if (format.indexOf('mm') === -1) {
  49. seconds += minutes * 60
  50. } else {
  51. format = format.replace('mm', padZero(minutes))
  52. }
  53. if (format.indexOf('ss') === -1) {
  54. milliseconds += seconds * 1000
  55. } else {
  56. format = format.replace('ss', padZero(seconds))
  57. }
  58. return format.replace('SSS', padZero(milliseconds, 3))
  59. }
  60. export function isSameSecond(time1, time2) {
  61. return Math.floor(time1 / 1000) === Math.floor(time2 / 1000)
  62. }