How to compare time in javascript? How to compare time in javascript? javascript javascript

How to compare time in javascript?


use Date objects. Date.setHours() allows you to specify hour, minutes, seconds

var currentD = new Date();var startHappyHourD = new Date();startHappyHourD.setHours(17,30,0); // 5.30 pmvar endHappyHourD = new Date();endHappyHourD.setHours(18,30,0); // 6.30 pmconsole.log("happy hour?")if(currentD >= startHappyHourD && currentD < endHappyHourD ){    console.log("yes!");}else{    console.log("no, sorry! between 5.30pm and 6.30pm");}


Date.parse('25/09/2013 13:31') > Date.parse('25/09/2013 9:15')

EDIT:

Note that you are parsing an arbitrary date that you're not interested in, it just needs to be the same on both sides.


Assuming you are not interested in time zones and only need to compare two formatted time strings in 24h time format, you can just compare strings.

"09:12" > "12:22" //false"09:12" < "12:22" //true"08:12" > "09:22" //false"08:12" < "09:22" //true

Strings has to be normalised to hh:mm, otherwise you will get unexpected results like:

"9:12" > "12:22" //true