@intility/bifrost-react
Version:
React library for Intility's design system, Bifrost.
26 lines (25 loc) • 1.16 kB
JavaScript
/**
* Construct a Duration object based on start and end dates. Used internally by
* `<FormatDuration>` and `<FormatRelativeTime>`.
* @param start Start date
* @param end End date
* @returns A tuple containing the largest appropriate
* Intl.RelativeTimeFormatUnit and the duration in that unit
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/format
*/
export default function getDuration(start, end) {
const durationInMs = end.getTime() - start.getTime();
const seconds = Math.round(durationInMs / 1000);
const minutes = seconds / 60;
const hours = minutes / 60;
const days = hours / 24;
const months = days / 30.44; // Average days per month (365.25 / 12)
const years = days / 365.25; // Account for leap years
if (Math.abs(years) >= 1) return ["years", Math.round(years)];
if (Math.abs(months) >= 1) return ["months", Math.round(months)];
if (Math.abs(days) >= 1) return ["days", Math.round(days)];
if (Math.abs(hours) >= 1) return ["hours", Math.round(hours)];
if (Math.abs(minutes) >= 1) return ["minutes", Math.round(minutes)];
return ["seconds", seconds];
}