DEV Community

loading...
Cover image for JavaScript Relative Time

JavaScript Relative Time

Lawrence Chen
・1 min read

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);
        }
    }
};

Enter fullscreen mode Exit fullscreen mode

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);
        }
    }
};
Enter fullscreen mode Exit fullscreen mode

Credits

https://stackoverflow.com/questions/6108819/javascript-timestamp-to-relative-time

Discussion (0)