intlFormatDistance.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import { normalizeDates } from "./_lib/normalizeDates.js";
  2. import {
  3. secondsInDay,
  4. secondsInHour,
  5. secondsInMinute,
  6. secondsInMonth,
  7. secondsInQuarter,
  8. secondsInWeek,
  9. secondsInYear,
  10. } from "./constants.js";
  11. import { differenceInCalendarDays } from "./differenceInCalendarDays.js";
  12. import { differenceInCalendarMonths } from "./differenceInCalendarMonths.js";
  13. import { differenceInCalendarQuarters } from "./differenceInCalendarQuarters.js";
  14. import { differenceInCalendarWeeks } from "./differenceInCalendarWeeks.js";
  15. import { differenceInCalendarYears } from "./differenceInCalendarYears.js";
  16. import { differenceInHours } from "./differenceInHours.js";
  17. import { differenceInMinutes } from "./differenceInMinutes.js";
  18. import { differenceInSeconds } from "./differenceInSeconds.js";
  19. /**
  20. * The {@link intlFormatDistance} function options.
  21. */
  22. /**
  23. * The unit used to format the distance in {@link intlFormatDistance}.
  24. */
  25. /**
  26. * @name intlFormatDistance
  27. * @category Common Helpers
  28. * @summary Formats distance between two dates in a human-readable format
  29. * @description
  30. * The function calculates the difference between two dates and formats it as a human-readable string.
  31. *
  32. * The function will pick the most appropriate unit depending on the distance between dates. For example, if the distance is a few hours, it might return `x hours`. If the distance is a few months, it might return `x months`.
  33. *
  34. * You can also specify a unit to force using it regardless of the distance to get a result like `123456 hours`.
  35. *
  36. * See the table below for the unit picking logic:
  37. *
  38. * | Distance between dates | Result (past) | Result (future) |
  39. * | ---------------------- | -------------- | --------------- |
  40. * | 0 seconds | now | now |
  41. * | 1-59 seconds | X seconds ago | in X seconds |
  42. * | 1-59 minutes | X minutes ago | in X minutes |
  43. * | 1-23 hours | X hours ago | in X hours |
  44. * | 1 day | yesterday | tomorrow |
  45. * | 2-6 days | X days ago | in X days |
  46. * | 7 days | last week | next week |
  47. * | 8 days-1 month | X weeks ago | in X weeks |
  48. * | 1 month | last month | next month |
  49. * | 2-3 months | X months ago | in X months |
  50. * | 1 quarter | last quarter | next quarter |
  51. * | 2-3 quarters | X quarters ago | in X quarters |
  52. * | 1 year | last year | next year |
  53. * | 2+ years | X years ago | in X years |
  54. *
  55. * @param laterDate - The date
  56. * @param earlierDate - The date to compare with.
  57. * @param options - An object with options.
  58. * See MDN for details [Locale identification and negotiation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation)
  59. * The narrow one could be similar to the short one for some locales.
  60. *
  61. * @returns The distance in words according to language-sensitive relative time formatting.
  62. *
  63. * @throws `date` must not be Invalid Date
  64. * @throws `baseDate` must not be Invalid Date
  65. * @throws `options.unit` must not be invalid Unit
  66. * @throws `options.locale` must not be invalid locale
  67. * @throws `options.localeMatcher` must not be invalid localeMatcher
  68. * @throws `options.numeric` must not be invalid numeric
  69. * @throws `options.style` must not be invalid style
  70. *
  71. * @example
  72. * // What is the distance between the dates when the fist date is after the second?
  73. * intlFormatDistance(
  74. * new Date(1986, 3, 4, 11, 30, 0),
  75. * new Date(1986, 3, 4, 10, 30, 0)
  76. * )
  77. * //=> 'in 1 hour'
  78. *
  79. * // What is the distance between the dates when the fist date is before the second?
  80. * intlFormatDistance(
  81. * new Date(1986, 3, 4, 10, 30, 0),
  82. * new Date(1986, 3, 4, 11, 30, 0)
  83. * )
  84. * //=> '1 hour ago'
  85. *
  86. * @example
  87. * // Use the unit option to force the function to output the result in quarters. Without setting it, the example would return "next year"
  88. * intlFormatDistance(
  89. * new Date(1987, 6, 4, 10, 30, 0),
  90. * new Date(1986, 3, 4, 10, 30, 0),
  91. * { unit: 'quarter' }
  92. * )
  93. * //=> 'in 5 quarters'
  94. *
  95. * @example
  96. * // Use the locale option to get the result in Spanish. Without setting it, the example would return "in 1 hour".
  97. * intlFormatDistance(
  98. * new Date(1986, 3, 4, 11, 30, 0),
  99. * new Date(1986, 3, 4, 10, 30, 0),
  100. * { locale: 'es' }
  101. * )
  102. * //=> 'dentro de 1 hora'
  103. *
  104. * @example
  105. * // Use the numeric option to force the function to use numeric values. Without setting it, the example would return "tomorrow".
  106. * intlFormatDistance(
  107. * new Date(1986, 3, 5, 11, 30, 0),
  108. * new Date(1986, 3, 4, 11, 30, 0),
  109. * { numeric: 'always' }
  110. * )
  111. * //=> 'in 1 day'
  112. *
  113. * @example
  114. * // Use the style option to force the function to use short values. Without setting it, the example would return "in 2 years".
  115. * intlFormatDistance(
  116. * new Date(1988, 3, 4, 11, 30, 0),
  117. * new Date(1986, 3, 4, 11, 30, 0),
  118. * { style: 'short' }
  119. * )
  120. * //=> 'in 2 yr'
  121. */
  122. export function intlFormatDistance(laterDate, earlierDate, options) {
  123. let value = 0;
  124. let unit;
  125. const [laterDate_, earlierDate_] = normalizeDates(
  126. options?.in,
  127. laterDate,
  128. earlierDate,
  129. );
  130. if (!options?.unit) {
  131. // Get the unit based on diffInSeconds calculations if no unit is specified
  132. const diffInSeconds = differenceInSeconds(laterDate_, earlierDate_); // The smallest unit
  133. if (Math.abs(diffInSeconds) < secondsInMinute) {
  134. value = differenceInSeconds(laterDate_, earlierDate_);
  135. unit = "second";
  136. } else if (Math.abs(diffInSeconds) < secondsInHour) {
  137. value = differenceInMinutes(laterDate_, earlierDate_);
  138. unit = "minute";
  139. } else if (
  140. Math.abs(diffInSeconds) < secondsInDay &&
  141. Math.abs(differenceInCalendarDays(laterDate_, earlierDate_)) < 1
  142. ) {
  143. value = differenceInHours(laterDate_, earlierDate_);
  144. unit = "hour";
  145. } else if (
  146. Math.abs(diffInSeconds) < secondsInWeek &&
  147. (value = differenceInCalendarDays(laterDate_, earlierDate_)) &&
  148. Math.abs(value) < 7
  149. ) {
  150. unit = "day";
  151. } else if (Math.abs(diffInSeconds) < secondsInMonth) {
  152. value = differenceInCalendarWeeks(laterDate_, earlierDate_);
  153. unit = "week";
  154. } else if (Math.abs(diffInSeconds) < secondsInQuarter) {
  155. value = differenceInCalendarMonths(laterDate_, earlierDate_);
  156. unit = "month";
  157. } else if (Math.abs(diffInSeconds) < secondsInYear) {
  158. if (differenceInCalendarQuarters(laterDate_, earlierDate_) < 4) {
  159. // To filter out cases that are less than a year but match 4 quarters
  160. value = differenceInCalendarQuarters(laterDate_, earlierDate_);
  161. unit = "quarter";
  162. } else {
  163. value = differenceInCalendarYears(laterDate_, earlierDate_);
  164. unit = "year";
  165. }
  166. } else {
  167. value = differenceInCalendarYears(laterDate_, earlierDate_);
  168. unit = "year";
  169. }
  170. } else {
  171. // Get the value if unit is specified
  172. unit = options?.unit;
  173. if (unit === "second") {
  174. value = differenceInSeconds(laterDate_, earlierDate_);
  175. } else if (unit === "minute") {
  176. value = differenceInMinutes(laterDate_, earlierDate_);
  177. } else if (unit === "hour") {
  178. value = differenceInHours(laterDate_, earlierDate_);
  179. } else if (unit === "day") {
  180. value = differenceInCalendarDays(laterDate_, earlierDate_);
  181. } else if (unit === "week") {
  182. value = differenceInCalendarWeeks(laterDate_, earlierDate_);
  183. } else if (unit === "month") {
  184. value = differenceInCalendarMonths(laterDate_, earlierDate_);
  185. } else if (unit === "quarter") {
  186. value = differenceInCalendarQuarters(laterDate_, earlierDate_);
  187. } else if (unit === "year") {
  188. value = differenceInCalendarYears(laterDate_, earlierDate_);
  189. }
  190. }
  191. const rtf = new Intl.RelativeTimeFormat(options?.locale, {
  192. numeric: "auto",
  193. ...options,
  194. });
  195. return rtf.format(value, unit);
  196. }
  197. // Fallback for modularized imports:
  198. export default intlFormatDistance;