UNPKG

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