formatDistance.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import { defaultLocale } from "./_lib/defaultLocale.js";
  2. import { getDefaultOptions } from "./_lib/defaultOptions.js";
  3. import { getTimezoneOffsetInMilliseconds } from "./_lib/getTimezoneOffsetInMilliseconds.js";
  4. import { normalizeDates } from "./_lib/normalizeDates.js";
  5. import { compareAsc } from "./compareAsc.js";
  6. import { minutesInDay, minutesInMonth } from "./constants.js";
  7. import { differenceInMonths } from "./differenceInMonths.js";
  8. import { differenceInSeconds } from "./differenceInSeconds.js";
  9. /**
  10. * The {@link formatDistance} function options.
  11. */
  12. /**
  13. * @name formatDistance
  14. * @category Common Helpers
  15. * @summary Return the distance between the given dates in words.
  16. *
  17. * @description
  18. * Return the distance between the given dates in words.
  19. *
  20. * | Distance between dates | Result |
  21. * |-------------------------------------------------------------------|---------------------|
  22. * | 0 ... 30 secs | less than a minute |
  23. * | 30 secs ... 1 min 30 secs | 1 minute |
  24. * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes |
  25. * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour |
  26. * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours |
  27. * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day |
  28. * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days |
  29. * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month |
  30. * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months |
  31. * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months |
  32. * | 1 yr ... 1 yr 3 months | about 1 year |
  33. * | 1 yr 3 months ... 1 yr 9 month s | over 1 year |
  34. * | 1 yr 9 months ... 2 yrs | almost 2 years |
  35. * | N yrs ... N yrs 3 months | about N years |
  36. * | N yrs 3 months ... N yrs 9 months | over N years |
  37. * | N yrs 9 months ... N+1 yrs | almost N+1 years |
  38. *
  39. * With `options.includeSeconds == true`:
  40. * | Distance between dates | Result |
  41. * |------------------------|----------------------|
  42. * | 0 secs ... 5 secs | less than 5 seconds |
  43. * | 5 secs ... 10 secs | less than 10 seconds |
  44. * | 10 secs ... 20 secs | less than 20 seconds |
  45. * | 20 secs ... 40 secs | half a minute |
  46. * | 40 secs ... 60 secs | less than a minute |
  47. * | 60 secs ... 90 secs | 1 minute |
  48. *
  49. * @param laterDate - The date
  50. * @param earlierDate - The date to compare with
  51. * @param options - An object with options
  52. *
  53. * @returns The distance in words
  54. *
  55. * @throws `date` must not be Invalid Date
  56. * @throws `baseDate` must not be Invalid Date
  57. * @throws `options.locale` must contain `formatDistance` property
  58. *
  59. * @example
  60. * // What is the distance between 2 July 2014 and 1 January 2015?
  61. * const result = formatDistance(new Date(2014, 6, 2), new Date(2015, 0, 1))
  62. * //=> '6 months'
  63. *
  64. * @example
  65. * // What is the distance between 1 January 2015 00:00:15
  66. * // and 1 January 2015 00:00:00, including seconds?
  67. * const result = formatDistance(
  68. * new Date(2015, 0, 1, 0, 0, 15),
  69. * new Date(2015, 0, 1, 0, 0, 0),
  70. * { includeSeconds: true }
  71. * )
  72. * //=> 'less than 20 seconds'
  73. *
  74. * @example
  75. * // What is the distance from 1 January 2016
  76. * // to 1 January 2015, with a suffix?
  77. * const result = formatDistance(new Date(2015, 0, 1), new Date(2016, 0, 1), {
  78. * addSuffix: true
  79. * })
  80. * //=> 'about 1 year ago'
  81. *
  82. * @example
  83. * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto?
  84. * import { eoLocale } from 'date-fns/locale/eo'
  85. * const result = formatDistance(new Date(2016, 7, 1), new Date(2015, 0, 1), {
  86. * locale: eoLocale
  87. * })
  88. * //=> 'pli ol 1 jaro'
  89. */
  90. export function formatDistance(laterDate, earlierDate, options) {
  91. const defaultOptions = getDefaultOptions();
  92. const locale = options?.locale ?? defaultOptions.locale ?? defaultLocale;
  93. const minutesInAlmostTwoDays = 2520;
  94. const comparison = compareAsc(laterDate, earlierDate);
  95. if (isNaN(comparison)) throw new RangeError("Invalid time value");
  96. const localizeOptions = Object.assign({}, options, {
  97. addSuffix: options?.addSuffix,
  98. comparison: comparison,
  99. });
  100. const [laterDate_, earlierDate_] = normalizeDates(
  101. options?.in,
  102. ...(comparison > 0 ? [earlierDate, laterDate] : [laterDate, earlierDate]),
  103. );
  104. const seconds = differenceInSeconds(earlierDate_, laterDate_);
  105. const offsetInSeconds =
  106. (getTimezoneOffsetInMilliseconds(earlierDate_) -
  107. getTimezoneOffsetInMilliseconds(laterDate_)) /
  108. 1000;
  109. const minutes = Math.round((seconds - offsetInSeconds) / 60);
  110. let months;
  111. // 0 up to 2 mins
  112. if (minutes < 2) {
  113. if (options?.includeSeconds) {
  114. if (seconds < 5) {
  115. return locale.formatDistance("lessThanXSeconds", 5, localizeOptions);
  116. } else if (seconds < 10) {
  117. return locale.formatDistance("lessThanXSeconds", 10, localizeOptions);
  118. } else if (seconds < 20) {
  119. return locale.formatDistance("lessThanXSeconds", 20, localizeOptions);
  120. } else if (seconds < 40) {
  121. return locale.formatDistance("halfAMinute", 0, localizeOptions);
  122. } else if (seconds < 60) {
  123. return locale.formatDistance("lessThanXMinutes", 1, localizeOptions);
  124. } else {
  125. return locale.formatDistance("xMinutes", 1, localizeOptions);
  126. }
  127. } else {
  128. if (minutes === 0) {
  129. return locale.formatDistance("lessThanXMinutes", 1, localizeOptions);
  130. } else {
  131. return locale.formatDistance("xMinutes", minutes, localizeOptions);
  132. }
  133. }
  134. // 2 mins up to 0.75 hrs
  135. } else if (minutes < 45) {
  136. return locale.formatDistance("xMinutes", minutes, localizeOptions);
  137. // 0.75 hrs up to 1.5 hrs
  138. } else if (minutes < 90) {
  139. return locale.formatDistance("aboutXHours", 1, localizeOptions);
  140. // 1.5 hrs up to 24 hrs
  141. } else if (minutes < minutesInDay) {
  142. const hours = Math.round(minutes / 60);
  143. return locale.formatDistance("aboutXHours", hours, localizeOptions);
  144. // 1 day up to 1.75 days
  145. } else if (minutes < minutesInAlmostTwoDays) {
  146. return locale.formatDistance("xDays", 1, localizeOptions);
  147. // 1.75 days up to 30 days
  148. } else if (minutes < minutesInMonth) {
  149. const days = Math.round(minutes / minutesInDay);
  150. return locale.formatDistance("xDays", days, localizeOptions);
  151. // 1 month up to 2 months
  152. } else if (minutes < minutesInMonth * 2) {
  153. months = Math.round(minutes / minutesInMonth);
  154. return locale.formatDistance("aboutXMonths", months, localizeOptions);
  155. }
  156. months = differenceInMonths(earlierDate_, laterDate_);
  157. // 2 months up to 12 months
  158. if (months < 12) {
  159. const nearestMonth = Math.round(minutes / minutesInMonth);
  160. return locale.formatDistance("xMonths", nearestMonth, localizeOptions);
  161. // 1 year up to max Date
  162. } else {
  163. const monthsSinceStartOfYear = months % 12;
  164. const years = Math.trunc(months / 12);
  165. // N years up to 1 years 3 months
  166. if (monthsSinceStartOfYear < 3) {
  167. return locale.formatDistance("aboutXYears", years, localizeOptions);
  168. // N years 3 months up to N years 9 months
  169. } else if (monthsSinceStartOfYear < 9) {
  170. return locale.formatDistance("overXYears", years, localizeOptions);
  171. // N years 9 months up to N year 12 months
  172. } else {
  173. return locale.formatDistance("almostXYears", years + 1, localizeOptions);
  174. }
  175. }
  176. }
  177. // Fallback for modularized imports:
  178. export default formatDistance;