moment relative time

Moment Relative Time in HTML

As a blogger, I have used Moment.js to display dates and times in a more readable format. One of the features that I often use is the "relative time" function, which displays how long ago a certain date or time was.

To use Moment.js, you first need to include the library in your HTML file:

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
</head>

Once you have included the library, you can use the "fromNow" function to display relative time:

<div id="example"></div>

<script>
  var date = moment("2021-09-01T12:00:00");
  var relativeTime = date.fromNow();
  document.getElementById("example").innerHTML = relativeTime;
</script>

The above code will display "3 days ago" on the page, as that is how long ago September 1st, 2021 was from the current date. You can also customize the text that is displayed for certain time periods, such as "a few seconds ago" or "in 5 years".

Another way to use Moment.js is to display the difference between two dates or times:

<div id="example"></div>

<script>
  var start = moment("2021-09-01T12:00:00");
  var end = moment("2021-09-04T12:00:00");
  var difference = end.diff(start, 'days');
  document.getElementById("example").innerHTML = difference + " days";
</script>

This code will display "3 days" on the page, as that is the difference between September 1st and September 4th.

In conclusion, Moment.js is a powerful tool for displaying dates and times in a more user-friendly format. The "relative time" function is especially useful for displaying how long ago a certain date or time was, and can be easily customized to fit your needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe