I would like to know how I can make a function that would take a timestamp and returns a relative time format that would display for example in 2 hours and 15 minutes, in 2 minutes and 15 seconds, one day and 6 hours ago, 6 hours and 13 minutes ago.
It has to use Intl.RelativeTimeFormat so that it is localized automatically.
I already have this function but it only display one unit instead of two at the same time.
const fromNow = function (timestamp) {
const now = Date.now();
const diff = timestamp - now;
const days = diff / (1000 * 60 * 60 * 24);
const hours = (diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
const minutes = (diff % (1000 * 60 * 60)) / (1000 * 60);
const seconds = (diff % (1000 * 60)) / 1000;
const relative = new Intl.RelativeTimeFormat();
if (diff > 0) {
// If the difference is positive, the timestamp is in the future
if (days >= 1) {
return `${relative.format(Math.round(days), "day")}`;
}
if (hours >= 1) {
return relative.format(Math.round(hours), "hour");
}
if (minutes >= 1) {
return relative.format(Math.round(minutes), "minute");
}
if (seconds >= 0) {
return relative.format(Math.round(seconds), "second");
}
}
if (diff < 0) {
// If the difference is negative, the timestamp is in the past
if (Math.abs(days) >= 1) {
return relative.format(Math.round(days), "day");
}
if (Math.abs(hours) >= 1) {
return relative.format(Math.round(hours), "hour");
}
if (Math.abs(minutes) >= 1) {
return relative.format(Math.round(minutes), "minute");
}
if (Math.abs(seconds) >= 0) {
return relative.format(Math.round(seconds), "second");
}
}
return "";
};
export default fromNow;