How to convert date to hours from now using moment.js?

Member

by jerad , in category: Javascript , 3 months ago

How to convert date to hours from now using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 3 months ago

@jerad 

To convert a date to the number of hours from now using Moment.js, you can follow these steps:

  1. Include the Moment.js library in your HTML file. You can either download the library and link it with a script tag or use a CDN. For example:
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>


  1. Suppose you have a specific date or timestamp that you want to convert. Create a Moment.js object for that date. For example, to get the number of hours from now for a specific date (e.g., "2022-01-01 09:00:00"), you can use the moment() function:
1
const targetDate = moment("2022-01-01 09:00:00");


  1. Calculate the difference between the current date/time and the target date, and get the duration in hours using the diff() and hours() functions. To get the difference from the current date/time, you can use moment(). For example:
1
2
const now = moment();
const hoursFromNow = targetDate.diff(now, 'hours');


  1. Print out the result:
1
console.log(hoursFromNow);


Here's a complete example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
  <title>Date to Hours from Now</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
  <script>
    window.onload = function() {
      const targetDate = moment("2022-01-01 09:00:00");
      const now = moment();
      const hoursFromNow = targetDate.diff(now, 'hours');
      console.log(hoursFromNow);
    };
  </script>
</head>
<body>
</body>
</html>


In this example, the output will be the number of hours from the current time to the target date/time ("2022-01-01 09:00:00").