JavaScript Relative Time
Lawrence Chen
Posted on July 5, 2021
I've found that Day.js and Moment.js's relative time support to be buggy, especially when dealing with very recent timestamps.
Here's an implementation in TypeScript:
// much love https://stackoverflow.com/questions/6108819/javascript-timestamp-to-relative-time
const units = {
year: 24 * 60 * 60 * 1000 * 365,
month: (24 * 60 * 60 * 1000 * 365) / 12,
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
second: 1000
};
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
export const getRelativeTime = (d1: Date, d2 = new Date()): string => {
const elapsed = d1.getTime() - d2.getTime();
// "Math.abs" accounts for both "past" & "future" scenarios
for (const u in units) {
if (Math.abs(elapsed) > units[u] || u == 'second') {
return rtf.format(Math.round(elapsed / units[u]), u as Intl.RelativeTimeFormatUnit);
}
}
};
and raw JavaScript:
// much love https://stackoverflow.com/questions/6108819/javascript-timestamp-to-relative-time
const units = {
year: 24 * 60 * 60 * 1000 * 365,
month: (24 * 60 * 60 * 1000 * 365) / 12,
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
second: 1000
};
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
export const getRelativeTime = (d1, d2 = new Date()) => {
const elapsed = d1.getTime() - d2.getTime();
// "Math.abs" accounts for both "past" & "future" scenarios
for (const u in units) {
if (Math.abs(elapsed) > units[u] || u == 'second') {
return rtf.format(Math.round(elapsed / units[u]), u as Intl.RelativeTimeFormatUnit);
}
}
};
Credits
https://stackoverflow.com/questions/6108819/javascript-timestamp-to-relative-time
💖 💪 🙅 🚩
Lawrence Chen
Posted on July 5, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Sortie de TypeScript 5.7 RC, nouvelle alternative à npm, avenir des frameworks JavaScript - Cette semaine en JS
November 26, 2024
testing L'attaque des clones mutants : améliorez la fiabilité de vos tests à l'aide des tests de mutation
November 26, 2024