ce6753f18346e3fd080bc9ba2f693f762c6255d6b8b48ee7328fcb4716750a0a5c0458a7f762f586591231820f66fd49e35f45ed811fdad4e0561fcf186d1c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { createDuration } from './create';
  2. var round = Math.round;
  3. var thresholds = {
  4. s: 45, // seconds to minute
  5. m: 45, // minutes to hour
  6. h: 22, // hours to day
  7. d: 26, // days to month
  8. M: 11 // months to year
  9. };
  10. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  11. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  12. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  13. }
  14. function relativeTime (posNegDuration, withoutSuffix, locale) {
  15. var duration = createDuration(posNegDuration).abs();
  16. var seconds = round(duration.as('s'));
  17. var minutes = round(duration.as('m'));
  18. var hours = round(duration.as('h'));
  19. var days = round(duration.as('d'));
  20. var months = round(duration.as('M'));
  21. var years = round(duration.as('y'));
  22. var a = seconds < thresholds.s && ['s', seconds] ||
  23. minutes <= 1 && ['m'] ||
  24. minutes < thresholds.m && ['mm', minutes] ||
  25. hours <= 1 && ['h'] ||
  26. hours < thresholds.h && ['hh', hours] ||
  27. days <= 1 && ['d'] ||
  28. days < thresholds.d && ['dd', days] ||
  29. months <= 1 && ['M'] ||
  30. months < thresholds.M && ['MM', months] ||
  31. years <= 1 && ['y'] || ['yy', years];
  32. a[2] = withoutSuffix;
  33. a[3] = +posNegDuration > 0;
  34. a[4] = locale;
  35. return substituteTimeAgo.apply(null, a);
  36. }
  37. // This function allows you to set the rounding function for relative time strings
  38. export function getSetRelativeTimeRounding (roundingFunction) {
  39. if (roundingFunction === undefined) {
  40. return round;
  41. }
  42. if (typeof(roundingFunction) === 'function') {
  43. round = roundingFunction;
  44. return true;
  45. }
  46. return false;
  47. }
  48. // This function allows you to set a threshold for relative time strings
  49. export function getSetRelativeTimeThreshold (threshold, limit) {
  50. if (thresholds[threshold] === undefined) {
  51. return false;
  52. }
  53. if (limit === undefined) {
  54. return thresholds[threshold];
  55. }
  56. thresholds[threshold] = limit;
  57. return true;
  58. }
  59. export function humanize (withSuffix) {
  60. var locale = this.localeData();
  61. var output = relativeTime(this, !withSuffix, locale);
  62. if (withSuffix) {
  63. output = locale.pastFuture(+this, output);
  64. }
  65. return locale.postformat(output);
  66. }