UNPKG

2.3 kBJavaScriptView Raw
1import { normalizeInterval } from "./_lib/normalizeInterval.js";
2import { add } from "./add.js";
3import { differenceInDays } from "./differenceInDays.js";
4import { differenceInHours } from "./differenceInHours.js";
5import { differenceInMinutes } from "./differenceInMinutes.js";
6import { differenceInMonths } from "./differenceInMonths.js";
7import { differenceInSeconds } from "./differenceInSeconds.js";
8import { differenceInYears } from "./differenceInYears.js";
9
10/**
11 * The {@link intervalToDuration} function options.
12 */
13
14/**
15 * @name intervalToDuration
16 * @category Common Helpers
17 * @summary Convert interval to duration
18 *
19 * @description
20 * Convert an interval object to a duration object.
21 *
22 * @param interval - The interval to convert to duration
23 * @param options - The context options
24 *
25 * @returns The duration object
26 *
27 * @example
28 * // Get the duration between January 15, 1929 and April 4, 1968.
29 * intervalToDuration({
30 * start: new Date(1929, 0, 15, 12, 0, 0),
31 * end: new Date(1968, 3, 4, 19, 5, 0)
32 * });
33 * //=> { years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 }
34 */
35export function intervalToDuration(interval, options) {
36 const { start, end } = normalizeInterval(options?.in, interval);
37 const duration = {};
38
39 const years = differenceInYears(end, start);
40 if (years) duration.years = years;
41
42 const remainingMonths = add(start, { years: duration.years });
43 const months = differenceInMonths(end, remainingMonths);
44 if (months) duration.months = months;
45
46 const remainingDays = add(remainingMonths, { months: duration.months });
47 const days = differenceInDays(end, remainingDays);
48 if (days) duration.days = days;
49
50 const remainingHours = add(remainingDays, { days: duration.days });
51 const hours = differenceInHours(end, remainingHours);
52 if (hours) duration.hours = hours;
53
54 const remainingMinutes = add(remainingHours, { hours: duration.hours });
55 const minutes = differenceInMinutes(end, remainingMinutes);
56 if (minutes) duration.minutes = minutes;
57
58 const remainingSeconds = add(remainingMinutes, { minutes: duration.minutes });
59 const seconds = differenceInSeconds(end, remainingSeconds);
60 if (seconds) duration.seconds = seconds;
61
62 return duration;
63}
64
65// Fallback for modularized imports:
66export default intervalToDuration;