EventMapper/assets/scripts/modules/relative_time.js

54 lines
1.3 KiB
JavaScript
Raw Normal View History

2024-06-03 03:54:02 +00:00
// in miliseconds
export const units = {
year: 24 * 60 * 60 * 1000 * 365,
month: (24 * 60 * 60 * 1000 * 365) / 12,
2024-06-12 02:52:08 +00:00
week: 7 * 24 * 60 * 60 * 1000,
2024-06-03 03:54:02 +00:00
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
second: 1000,
};
export function getRelativeTime(d1, d2, locale) {
let rtf = new Intl.RelativeTimeFormat(locale, {
numeric: "auto",
});
let elapsed = d1 - d2;
2024-06-12 02:52:08 +00:00
if (Math.abs(elapsed) >= units.year) {
return d1.toLocaleDateString(locale, {
weekday: "long",
month: "long",
day: "numeric",
year: "numeric",
});
} else if (Math.abs(elapsed) >= units.day) {
return d1.toLocaleDateString(locale, {
weekday: "long",
month: "long",
day: "numeric",
});
}
2024-06-03 03:54:02 +00:00
// "Math.abs" accounts for both "past" & "future" scenarios
for (var u in units)
if (Math.abs(elapsed) > units[u] || u == "second")
return rtf.format(Math.round(elapsed / units[u]), u);
}
2024-06-04 22:54:40 +00:00
export function sameDay(d1, d2) {
return Math.abs(d2.getTime() - d1.getTime()) < units.day;
}
export function DatetoLocaleDynamicString(d1, ref, lang) {
if (sameDay(d1, ref))
return d1.toLocaleTimeString(lang, {
timeStyle: "short",
});
else
return d1.toLocaleDateString(lang, {
dateStyle: "short",
});
2024-06-12 02:52:08 +00:00
}