How to compare time with moment.js?

by aniya.jaskolski , in category: Javascript , 5 months ago

How to compare time with moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 5 months ago

@aniya.jaskolski 

To compare times using Moment.js, you can use the isBefore(), isSame(), and isAfter() methods. Here's an example:

  1. First, make sure you have Moment.js installed and make it accessible in your script.
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>


  1. Convert your time values to Moment.js objects using the moment() function. You can specify the format of your time string using the second argument if it differs from the default format ("YYYY-MM-DDTHH:mm:ssZ").
1
2
3
const time1 = moment("09:30", "HH:mm");
const time2 = moment("12:45 PM", "hh:mm A");
const time3 = moment("18:00", "HH:mm");


  1. Compare the times using the isBefore(), isSame(), or isAfter() methods.
1
2
3
console.log(time1.isBefore(time2)); // true
console.log(time2.isSame(time3));   // false
console.log(time3.isAfter(time1));  // true


In this example, time1 is before time2, time2 is not the same as time3, and time3 is after time1.