duration.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * Represent a duration in seconds as a string
  3. *
  4. * @param value A finite number, or its string representation
  5. * @return Includes one or two `:` separators, and matches the pattern
  6. * `hhhh:mm:ss`, possibly with a leading `-` for negative values and a
  7. * trailing `.sss` part for non-integer input
  8. *
  9. * @example
  10. * ```js
  11. * var mf = new MessageFormat();
  12. *
  13. * mf.compile('It has been {D, duration}')({ D: 123 })
  14. * // 'It has been 2:03'
  15. *
  16. * mf.compile('Countdown: {D, duration}')({ D: -151200.42 })
  17. * // 'Countdown: -42:00:00.420'
  18. * ```
  19. */
  20. export function duration(value) {
  21. if (typeof value !== 'number')
  22. value = Number(value);
  23. if (!isFinite(value))
  24. return String(value);
  25. var sign = '';
  26. if (value < 0) {
  27. sign = '-';
  28. value = Math.abs(value);
  29. }
  30. else {
  31. value = Number(value);
  32. }
  33. var sec = value % 60;
  34. var parts = [Math.round(sec) === sec ? sec : sec.toFixed(3)];
  35. if (value < 60) {
  36. parts.unshift(0); // at least one : is required
  37. }
  38. else {
  39. value = Math.round((value - Number(parts[0])) / 60);
  40. parts.unshift(value % 60); // minutes
  41. if (value >= 60) {
  42. value = Math.round((value - Number(parts[0])) / 60);
  43. parts.unshift(value); // hours
  44. }
  45. }
  46. var first = parts.shift();
  47. return (sign +
  48. first +
  49. ':' +
  50. parts.map(function (n) { return (n < 10 ? '0' + String(n) : String(n)); }).join(':'));
  51. }