JavaScript time passed string from date
Want to have time strings like "n seconds ago" or "m months ago"? Here's a short script.
export function friendlyTimePassed(targetDate) {
let timeDifferenceMilliseconds = new Date().getTime()-targetDate.getTime();
const ms = 1000;
const min = 60 * ms;
const hrs = 60 * min;
const days = 24 * hrs;
const week = 7 * days;
const month = 30.41666666 * days;
const year = days * 365;
let diffSeconds = (timeDifferenceMilliseconds / ms).toFixed(0);
if (diffSeconds < 1) {
return "less then a second";
}
let diffMinutes = timeDifferenceMilliseconds / min;
if (diffMinutes < 1) {
return diffSeconds.toFixed(0) + " seconds ago";
}
let diffHours = timeDifferenceMilliseconds / hrs;
if (diffHours < 1) {
return diffMinutes.toFixed(0) + " minutes ago";
}
let diffDays = timeDifferenceMilliseconds / days;
if (diffDays < 1) {
return diffHours.toFixed(0) + " hours ago";
}
let diffWeeks = timeDifferenceMilliseconds / week;
if (diffWeeks < 1) {
return diffDays.toFixed(0) + " days ago";
}
let diffMonths = timeDifferenceMilliseconds / month;
if (diffMonths < 1) {
return diffWeeks.toFixed(0) + " weeks ago";
}
let diffYears = timeDifferenceMilliseconds / year;
if (diffYears < 1) {
return diffMonths.toFixed(0) + " months ago";
}
return diffYears + " years ago";
}
Feel free to use it or to make it significantly better :).