formatDistance.mjs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import { compareAsc } from "./compareAsc.mjs";
  2. import { minutesInDay, minutesInMonth } from "./constants.mjs";
  3. import { differenceInMonths } from "./differenceInMonths.mjs";
  4. import { differenceInSeconds } from "./differenceInSeconds.mjs";
  5. import { toDate } from "./toDate.mjs";
  6. import { defaultLocale } from "./_lib/defaultLocale.mjs";
  7. import { getDefaultOptions } from "./_lib/defaultOptions.mjs";
  8. import { getTimezoneOffsetInMilliseconds } from "./_lib/getTimezoneOffsetInMilliseconds.mjs";
  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. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  50. *
  51. * @param date - The date
  52. * @param baseDate - The date to compare with
  53. * @param options - An object with options
  54. *
  55. * @returns The distance in words
  56. *
  57. * @throws `date` must not be Invalid Date
  58. * @throws `baseDate` must not be Invalid Date
  59. * @throws `options.locale` must contain `formatDistance` property
  60. *
  61. * @example
  62. * // What is the distance between 2 July 2014 and 1 January 2015?
  63. * const result = formatDistance(new Date(2014, 6, 2), new Date(2015, 0, 1))
  64. * //=> '6 months'
  65. *
  66. * @example
  67. * // What is the distance between 1 January 2015 00:00:15
  68. * // and 1 January 2015 00:00:00, including seconds?
  69. * const result = formatDistance(
  70. * new Date(2015, 0, 1, 0, 0, 15),
  71. * new Date(2015, 0, 1, 0, 0, 0),
  72. * { includeSeconds: true }
  73. * )
  74. * //=> 'less than 20 seconds'
  75. *
  76. * @example
  77. * // What is the distance from 1 January 2016
  78. * // to 1 January 2015, with a suffix?
  79. * const result = formatDistance(new Date(2015, 0, 1), new Date(2016, 0, 1), {
  80. * addSuffix: true
  81. * })
  82. * //=> 'about 1 year ago'
  83. *
  84. * @example
  85. * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto?
  86. * import { eoLocale } from 'date-fns/locale/eo'
  87. * const result = formatDistance(new Date(2016, 7, 1), new Date(2015, 0, 1), {
  88. * locale: eoLocale
  89. * })
  90. * //=> 'pli ol 1 jaro'
  91. */
  92. export function formatDistance(date, baseDate, options) {
  93. const defaultOptions = getDefaultOptions();
  94. const locale = options?.locale ?? defaultOptions.locale ?? defaultLocale;
  95. const minutesInAlmostTwoDays = 2520;
  96. const comparison = compareAsc(date, baseDate);
  97. if (isNaN(comparison)) {
  98. throw new RangeError("Invalid time value");
  99. }
  100. const localizeOptions = Object.assign({}, options, {
  101. addSuffix: options?.addSuffix,
  102. comparison: comparison,
  103. });
  104. let dateLeft;
  105. let dateRight;
  106. if (comparison > 0) {
  107. dateLeft = toDate(baseDate);
  108. dateRight = toDate(date);
  109. } else {
  110. dateLeft = toDate(date);
  111. dateRight = toDate(baseDate);
  112. }
  113. const seconds = differenceInSeconds(dateRight, dateLeft);
  114. const offsetInSeconds =
  115. (getTimezoneOffsetInMilliseconds(dateRight) -
  116. getTimezoneOffsetInMilliseconds(dateLeft)) /
  117. 1000;
  118. const minutes = Math.round((seconds - offsetInSeconds) / 60);
  119. let months;
  120. // 0 up to 2 mins
  121. if (minutes < 2) {
  122. if (options?.includeSeconds) {
  123. if (seconds < 5) {
  124. return locale.formatDistance("lessThanXSeconds", 5, localizeOptions);
  125. } else if (seconds < 10) {
  126. return locale.formatDistance("lessThanXSeconds", 10, localizeOptions);
  127. } else if (seconds < 20) {
  128. return locale.formatDistance("lessThanXSeconds", 20, localizeOptions);
  129. } else if (seconds < 40) {
  130. return locale.formatDistance("halfAMinute", 0, localizeOptions);
  131. } else if (seconds < 60) {
  132. return locale.formatDistance("lessThanXMinutes", 1, localizeOptions);
  133. } else {
  134. return locale.formatDistance("xMinutes", 1, localizeOptions);
  135. }
  136. } else {
  137. if (minutes === 0) {
  138. return locale.formatDistance("lessThanXMinutes", 1, localizeOptions);
  139. } else {
  140. return locale.formatDistance("xMinutes", minutes, localizeOptions);
  141. }
  142. }
  143. // 2 mins up to 0.75 hrs
  144. } else if (minutes < 45) {
  145. return locale.formatDistance("xMinutes", minutes, localizeOptions);
  146. // 0.75 hrs up to 1.5 hrs
  147. } else if (minutes < 90) {
  148. return locale.formatDistance("aboutXHours", 1, localizeOptions);
  149. // 1.5 hrs up to 24 hrs
  150. } else if (minutes < minutesInDay) {
  151. const hours = Math.round(minutes / 60);
  152. return locale.formatDistance("aboutXHours", hours, localizeOptions);
  153. // 1 day up to 1.75 days
  154. } else if (minutes < minutesInAlmostTwoDays) {
  155. return locale.formatDistance("xDays", 1, localizeOptions);
  156. // 1.75 days up to 30 days
  157. } else if (minutes < minutesInMonth) {
  158. const days = Math.round(minutes / minutesInDay);
  159. return locale.formatDistance("xDays", days, localizeOptions);
  160. // 1 month up to 2 months
  161. } else if (minutes < minutesInMonth * 2) {
  162. months = Math.round(minutes / minutesInMonth);
  163. return locale.formatDistance("aboutXMonths", months, localizeOptions);
  164. }
  165. months = differenceInMonths(dateRight, dateLeft);
  166. // 2 months up to 12 months
  167. if (months < 12) {
  168. const nearestMonth = Math.round(minutes / minutesInMonth);
  169. return locale.formatDistance("xMonths", nearestMonth, localizeOptions);
  170. // 1 year up to max Date
  171. } else {
  172. const monthsSinceStartOfYear = months % 12;
  173. const years = Math.trunc(months / 12);
  174. // N years up to 1 years 3 months
  175. if (monthsSinceStartOfYear < 3) {
  176. return locale.formatDistance("aboutXYears", years, localizeOptions);
  177. // N years 3 months up to N years 9 months
  178. } else if (monthsSinceStartOfYear < 9) {
  179. return locale.formatDistance("overXYears", years, localizeOptions);
  180. // N years 9 months up to N year 12 months
  181. } else {
  182. return locale.formatDistance("almostXYears", years + 1, localizeOptions);
  183. }
  184. }
  185. }
  186. // Fallback for modularized imports:
  187. export default formatDistance;