utils.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Countdown
  2. const timeUnits = [['Y', 1000 * 60 * 60 * 24 * 365],
  3. // years
  4. ['M', 1000 * 60 * 60 * 24 * 30],
  5. // months
  6. ['D', 1000 * 60 * 60 * 24],
  7. // days
  8. ['H', 1000 * 60 * 60],
  9. // hours
  10. ['m', 1000 * 60],
  11. // minutes
  12. ['s', 1000],
  13. // seconds
  14. ['S', 1] // million seconds
  15. ];
  16. export function formatTimeStr(duration, format) {
  17. let leftDuration = duration;
  18. const escapeRegex = /\[[^\]]*]/g;
  19. const keepList = (format.match(escapeRegex) || []).map(str => str.slice(1, -1));
  20. const templateText = format.replace(escapeRegex, '[]');
  21. const replacedText = timeUnits.reduce((current, [name, unit]) => {
  22. if (current.includes(name)) {
  23. const value = Math.floor(leftDuration / unit);
  24. leftDuration -= value * unit;
  25. return current.replace(new RegExp(`${name}+`, 'g'), match => {
  26. const len = match.length;
  27. return value.toString().padStart(len, '0');
  28. });
  29. }
  30. return current;
  31. }, templateText);
  32. let index = 0;
  33. return replacedText.replace(escapeRegex, () => {
  34. const match = keepList[index];
  35. index += 1;
  36. return match;
  37. });
  38. }
  39. export function formatCounter(value, config, down) {
  40. const {
  41. format = ''
  42. } = config;
  43. const target = new Date(value).getTime();
  44. const current = Date.now();
  45. const diff = down ? Math.max(target - current, 0) : Math.max(current - target, 0);
  46. return formatTimeStr(diff, format);
  47. }