How to compare two different time in moment.js?

by darrion.kuhn , in category: Javascript , 5 months ago

How to compare two different time in moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 3 months ago

@darrion.kuhn 

To compare two different times in Moment.js, you can use the diff() method, which returns the difference between two moments in the specified unit of measurement.


Here's an example of how to compare two times:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var time1 = moment("09:30", "HH:mm");
var time2 = moment("12:15", "HH:mm");

// Compare the two times and get the difference in minutes
var diffInMinutes = time2.diff(time1, "minutes");

// Compare the two times and get the difference in hours
var diffInHours = time2.diff(time1, "hours");

// Compare the two times and get the difference in days
var diffInDays = time2.diff(time1, "days");

console.log("Difference in minutes:", diffInMinutes);
console.log("Difference in hours:", diffInHours);
console.log("Difference in days:", diffInDays);


In this example, we have two moments time1 and time2 representing different times. We then use the diff() method to compare them, passing the unit of measurement ("minutes", "hours", or "days") as the second argument. The result is stored in variables diffInMinutes, diffInHours, and diffInDays, respectively.


You can adjust the format used to create the moments (moment("09:30", "HH:mm")) according to your specific time format.