Skip to content
the poor coder

moment relative time

Poor Man
Published
Reading time
1 min read

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:

Text
<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:

Text
<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:

Text
<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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC