最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

datetime - JavaScript time compare - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question asked Aug 1, 2012 at 15:34 SinoSino 9903 gold badges12 silver badges27 bronze badges 2
  • For one, you're missing an else – sachleen Commented Aug 1, 2012 at 15:36
  • Ahh.. yeah I fixed that, still not working.. (stupid lol) – Sino Commented Aug 1, 2012 at 15:38
Add a ment  | 

4 Answers 4

Reset to default 6

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

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

...that's it!

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 pare the hours and minutes since that's what you have.

curr_hour > open_hour && curr_minute > open_minute

Why create date objects? Just use basic math.

var d = new Date();
var curr_hour = d.getHours();
var curr_minute = d.getMinutes();
var curr_time = curr_hour + curr_minute/60;

var open_time = 17;
var openClosed = curr_time > open_time ? "Open" : "Closed";

alert("Webshop is " + openClosed + ".");

Try this:

var d = new Date();
var curr_hour = d.getHours();
var curr_minute = d.getMinutes();
var curr_second = d.getSeconds();

if((curr_hour > 17) || (curr_hour == 17 && curr_minute == 0 && curr_second == 0 )){
   alert("Webshop is open");
} else {
   alert("Webshop is closed.");
}
发布评论

评论列表(0)

  1. 暂无评论