ad634a6f17887ac0ecea2f427547175f616f39fc74e3d1e6e1c8a63c9b3fdf7da971936a1b5775ad02916c76420bda27bfa3335184c17e97b7675cc779a550 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 a threshold for relative time strings
  38. export function getSetRelativeTimeThreshold (threshold, limit) {
  39. if (thresholds[threshold] === undefined) {
  40. return false;
  41. }
  42. if (limit === undefined) {
  43. return thresholds[threshold];
  44. }
  45. thresholds[threshold] = limit;
  46. return true;
  47. }
  48. export function humanize (withSuffix) {
  49. var locale = this.localeData();
  50. var output = relativeTime(this, !withSuffix, locale);
  51. if (withSuffix) {
  52. output = locale.pastFuture(+this, output);
  53. }
  54. return locale.postformat(output);
  55. }