Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript time compare

I have now the following code:

var d = new Date();
var curr_hour = d.getHours();
var curr_minute = d.getMinutes();
var curr_time = curr_hour + ":" + curr_minute;

var open_time = "17:00";

if(Date.parse ( curr_time ) > Date.parse ( open_time )){
   alert("Webshop is open");
} else {
   alert("Webshop is closed.");
}

What the code should do is.. if the current time is greater then 17:00 send the alert and if not, send the other alert.. All i get now is that it is closed.

like image 687
Sino Avatar asked Apr 14 '26 18:04

Sino


2 Answers

You don't need all that parsing, you already know getHours() method!

if(new Date().getHours() >= 17)

...that's it!

like image 93
Tomasz Nurkiewicz Avatar answered Apr 17 '26 07:04

Tomasz Nurkiewicz


You can't just parse time in hh:mm format. Give it an arbitrary date (Jan 1, 2012 in this case) to make it a full date object. The date doesn't matter as long as it's the same for both.

if(Date.parse('01/01/2012 ' + curr_time) > Date.parse ('01/01/2012 ' +  open_time)){
   console.log("open");
}else{
   console.log("closed");
}

A simpler approach would be to just compare the hours and minutes since that's what you have.

curr_hour > open_hour && curr_minute > open_minute
like image 21
sachleen Avatar answered Apr 17 '26 07:04

sachleen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!