admin管理员组

文章数量:1296373

How do you retrieve the hours and minutes of Date object and then display a message? If the time is between 9pm and 12am I want to display "We are closed", otherwise I want to display "We are open".

<script language="javascript"> 
<!-- 
    today = new Date();
    document.write('<BR>We are Open');
//--> 
</script> 

How do you retrieve the hours and minutes of Date object and then display a message? If the time is between 9pm and 12am I want to display "We are closed", otherwise I want to display "We are open".

<script language="javascript"> 
<!-- 
    today = new Date();
    document.write('<BR>We are Open');
//--> 
</script> 
Share edited Sep 3, 2015 at 21:03 Kulu Limpa 3,5411 gold badge23 silver badges31 bronze badges asked Dec 11, 2012 at 16:07 user1895103user1895103 411 gold badge1 silver badge5 bronze badges 2
  • I would use a setTimeout for displaying and removing the message. – EricG Commented Dec 11, 2012 at 16:11
  • Which has as an effect that if you visit the site before 9pm and you stay until 9pm, it will popup still @9pm. – EricG Commented Dec 11, 2012 at 16:16
Add a ment  | 

4 Answers 4

Reset to default 2

today is a Date, so you can use its functions. In your case, use today.getHours() and check whether it's >= 12 and < 21 to show the opened message. The closed message can appear in an else.

Note that this uses the client's time, so if you're using this on a web page worldwide, then you might be opened in Europe but at the same time closed in the US.

I'm not sure if I got the "time logic" correct (check the if statement), but this should be what you are looking for.

var objDate = new Date();
var hours = objDate.getHours();
if(hours >= 12 && hours <= 21){
    document.write('We Are Closed');
}
else{
    document.write('We are Open');
}

You can get Minutes And Hours From Date Using Following:

var d = new Date();
    var m = d.getMinutes();
    var h = d.getHours();

Compare your var h using following condition and get the desired result:

if(h>= 12 && h<= 21)

i usually use this kind of solution, which i'm posting just for knowledge (pimvdb's answer is more clear indeed)

var d = new Date();
var currtime = d.getHours() * 100 + d.getMinutes();

// now your currtime looks like 530 if it's 5.30am, or 1730 if it's 5.30 pm
// you can just do a simple parison between ints

if (currtime > 2000 and currtime < 800){
    // closed between 20:00 (8 pm) and 8:00 (8 am) as an example
    alert("We are closed");
}

you basically convert your time to an integer, making parison easier (thus not so much readable and mantainable)

本文标签: conditional statementsjavascript check time and display messageStack Overflow