Getting time difference from now

Intro

Working with raw timestamps is not user-friendly.

Instead of showing dates like “2024-05-10 10:15:43”,
we can display them in a more readable way:

– 5 minutes ago
– 2 days ago
– in 3 months

This is called relative time formatting.

Example Ouput

let us say today is 15-Apr-2026 and we send the input date string, the api will return date readable

Input Date StringDate ReadableTime Before / After
10-Apr-2025Thursday, 10 April 2025last year
20-May-2025Tuesday, 20 May 202511 months ago
10-Mar-2026Tuesday, 10 March 2026last month
20-Mar-2026Friday, 20 March 202626 days ago
10-Apr-2026Friday, 10 April 20265 days ago
22-Apr-2026Wednesday, 22 April 2026in 7 days
10-May-2026Sunday, 10 May 2026in 25 days
20-May-2026Wednesday, 20 May 2026next month
10-Apr-2027Saturday, 10 April 2027in 12 months
20-Apr-2027Tuesday, 20 April 2027next year

Try it yourself

Enter any date and see how it converts into relative time.

How it works

We calculate the difference between the current time and the given date.

Then we convert that difference into units like seconds, minutes, hours, days, months, or years.

Finally, we format it into readable text like “2 hours ago” or “in 5 days”.

Code Example

function getTimeAgo(dateStr) {
  const relativeTime = new RelativeTime(); // defaults to OS localen  
  let dateObj = new Date(dateStr); 
  return relativeTime.from(dateObj);
}

We can use JavaScript to convert a date into a readable relative time format.

For example, “2024-05-10T01:25:14.317Z” is less readable than “7 hours ago”.

I have used the relative-time library to simplify this conversion:
https://github.com/yairEO/relative-time

Full code available here:
https://github.com/khalilahmed232/khalilahmed232/tree/main/plain/date-time-ago

This makes date display much more user-friendly in real applications.

Using relative time formatting makes applications feel more modern and user-friendly, especially for feeds, comments, and activity logs.