Time Ago Util Function

May 13, 2023

Util Functions

Time Ago Util Function

Thuta Sann

Thuta Sann

In this section, I will demonstrate the TimeAgo Util Function in Javscript


Share This Snippet To :

Time Ago

TimeAgo Function is used to display how the time went through according to the current date time.

Example Usages - Feed Posts, Submitted Forms, etc.

/** * Format TimeAgo * @param { string } date - Date from the server * @example <caption>Example Usage</caption> * const ago = timeAgo(new Date(new Date().getTime() - 366 * 60 * 60 * 24 * 1000)); * @returns { string } TimeAgo Information */ export function timeAgo(date) { const formattedDate = Number(new Date(date)) const seconds = Math.floor((Number(new Date()) - formattedDate) / 1000); const intervals = { year: 31536000, month: 2592000, week: 604800, day: 86400, hour: 3600, minute: 60, second: 1, }; let interval; let count; for (const key in intervals) { if (seconds >= intervals[key]) { interval = key; count = Math.floor(seconds / intervals[key]); break; } } if (count === 1440 && interval === 'minute') { return 'Today'; } if (count === 1 && interval === 'day') { return 'Yesterday'; } if (!interval || !count) { return 'just now'; } return count + ' ' + interval + (count > 1 ? 's' : '') + ' ago'; } // Usages const ta1 = timeAgo(new Date(new Date().getTime() - 366 * 60 * 60 * 24 * 1000)); const ta2 = timeAgo(new Date(new Date().getTime() - 100 * 60 * 60 * 24 * 1000)); const ta3 = timeAgo(new Date(new Date().getTime() - 30 * 60 * 60 * 24 * 1000)); const ta4 = timeAgo(new Date(new Date().getTime() - 5 * 60 * 60 * 24 * 1000)); const ta5 = timeAgo(new Date(new Date().getTime() - 60 * 60 * 24 * 1000)); const ta6 = timeAgo(new Date(new Date().getTime() - 60 * 24 * 1000)); const ta7 = timeAgo(new Date(new Date().getTime() - 24 * 1000)); const ta8 = timeAgo(new Date(new Date().getTime() - 1000)); const ta9 = timeAgo(new Date());

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?