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

Function formatDuration

pkgs/core/src/formatDuration/index.ts:86–114  ·  view source on GitHub ↗
(
  duration: Duration,
  options?: FormatDurationOptions,
)

Source from the content-addressed store, hash-verified

84 * //=> '2 years, 9 months, 3 weeks'
85 */
86export function formatDuration(
87 duration: Duration,
88 options?: FormatDurationOptions,
89): string {
90 const defaultOptions = getDefaultOptions();
91 const locale = options?.locale ?? defaultOptions.locale ?? defaultLocale;
92 const format = options?.format ?? defaultFormat;
93 const zero = options?.zero ?? false;
94 const delimiter = options?.delimiter ?? " ";
95
96 if (!locale.formatDistance) {
97 return "";
98 }
99
100 const result = format
101 .reduce((acc, unit) => {
102 const token = `x${unit.replace(/(^.)/, (m) =>
103 m.toUpperCase(),
104 )}` as FormatDistanceToken;
105 const value = duration[unit];
106 if (value !== undefined && (zero || duration[unit])) {
107 return acc.concat(locale.formatDistance(token, value));
108 }
109 return acc;
110 }, [] as string[])
111 .join(delimiter);
112
113 return result;
114}

Callers 2

test.tsFile · 0.90
test.tsFile · 0.90

Calls 1

getDefaultOptionsFunction · 0.90

Tested by

no test coverage detected