Improve Date Readability With The timeAgo.js JavaScript Library

Category: Date & Time , Javascript | November 20, 2023
Author:Rawandev-top
Views Total:13 views
Official Page:Go to website
Last Update:November 20, 2023
License:MIT

Preview:

Improve Date Readability With The timeAgo.js JavaScript Library

Description:

Yet another timeago library to effortlessly display Datetime in a user-friendly format.

This lightweight JavaScript library transforms Datetime into easily understandable, relative time statements like ‘x days ago,’ ‘just now,’ etc. Currently supports formatting in 5 languages – English, German, Arabic, Kurdish Kurmanji, and Kurdish Sorani.

How to use it:

1. Download and load the timeAgo.js script in the HTML document.

<script src="timeAgo.js"></script>

2. Add your date string into the date-time attribute as follows:

<div class="timestamp" date-time="11/19/2023 01:23:45 AM"></div>
<div class="timestamp" date-time="11/19/2023 01:23:45 PM"></div>
<div class="timestamp" date-time="2022-11-18 01:23:45 AM"></div>
<div class="timestamp" date-time="2022-11-18 01:23:45 PM"></div>
<div class="timestamp" date-time="11/18/2023 01:23:45"></div>
<div class="timestamp" date-time="11/18/2023 20:23:45"></div>
<div class="timestamp" date-time="2023-11-18 20:23:45"></div>

3. Call the timeAgo() function and specify the language you want to use. That’s it.

const timeago = new TimeAgo("en");
document.querySelectorAll(".timestamp").forEach((element) => {
  const timestamp = new Date(element.getAttribute("date-time"));
  element.innerText = timeago.format(timestamp);
});

You Might Be Interested In:


Leave a Reply