MCPcopy
hub / github.com/date-fns/date-fns / formatDistance

Function formatDistance

pkgs/core/src/formatDistance/index.ts:100–208  ·  view source on GitHub ↗
(
  laterDate: DateArg<Date> & {},
  earlierDate: DateArg<Date> & {},
  options?: FormatDistanceOptions,
)

Source from the content-addressed store, hash-verified

98 * //=> 'pli ol 1 jaro'
99 */
100export function formatDistance(
101 laterDate: DateArg<Date> & {},
102 earlierDate: DateArg<Date> & {},
103 options?: FormatDistanceOptions,
104): string {
105 const defaultOptions = getDefaultOptions();
106 const locale = options?.locale ?? defaultOptions.locale ?? defaultLocale;
107 const minutesInAlmostTwoDays = 2520;
108
109 const comparison = compareAsc(laterDate, earlierDate);
110
111 if (isNaN(comparison)) throw new RangeError("Invalid time value");
112
113 const localizeOptions = Object.assign({}, options, {
114 addSuffix: options?.addSuffix,
115 comparison: comparison as -1 | 0 | 1,
116 });
117
118 const [laterDate_, earlierDate_] = normalizeDates(
119 options?.in,
120 ...(comparison > 0 ? [earlierDate, laterDate] : [laterDate, earlierDate]),
121 );
122
123 const seconds = differenceInSeconds(earlierDate_, laterDate_);
124 const offsetInSeconds =
125 (getTimezoneOffsetInMilliseconds(earlierDate_) -
126 getTimezoneOffsetInMilliseconds(laterDate_)) /
127 1000;
128 const minutes = Math.round((seconds - offsetInSeconds) / 60);
129 let months;
130
131 // 0 up to 2 mins
132 if (minutes < 2) {
133 if (options?.includeSeconds) {
134 if (seconds < 5) {
135 return locale.formatDistance("lessThanXSeconds", 5, localizeOptions);
136 } else if (seconds < 10) {
137 return locale.formatDistance("lessThanXSeconds", 10, localizeOptions);
138 } else if (seconds < 20) {
139 return locale.formatDistance("lessThanXSeconds", 20, localizeOptions);
140 } else if (seconds < 40) {
141 return locale.formatDistance("halfAMinute", 0, localizeOptions);
142 } else if (seconds < 60) {
143 return locale.formatDistance("lessThanXMinutes", 1, localizeOptions);
144 } else {
145 return locale.formatDistance("xMinutes", 1, localizeOptions);
146 }
147 } else {
148 if (minutes === 0) {
149 return locale.formatDistance("lessThanXMinutes", 1, localizeOptions);
150 } else {
151 return locale.formatDistance("xMinutes", minutes, localizeOptions);
152 }
153 }
154
155 // 2 mins up to 0.75 hrs
156 } else if (minutes < 45) {
157 return locale.formatDistance("xMinutes", minutes, localizeOptions);

Callers 4

test.tsFile · 0.90
_testFunction · 0.90
test.tsFile · 0.90
formatDistanceToNowFunction · 0.90

Calls 6

getDefaultOptionsFunction · 0.90
compareAscFunction · 0.90
normalizeDatesFunction · 0.90
differenceInSecondsFunction · 0.90
differenceInMonthsFunction · 0.90

Tested by

no test coverage detected