utils.js 1.3 KB

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