javascript javascript检查时间并显示消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13823856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:52:40  来源:igfitidea点击:

javascript check time and display message

javascriptconditional-statements

提问by user1895103

How do you retrieve the hours and minutes of Dateobject 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".

如何检索Date对象的小时和分钟,然后显示消息?如果时间在晚上 9 点到中午 12 点之间,我想显示“我们已关闭”,否则我想显示“我们已开放”。

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

回答by pimvdb

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

today是 a Date,所以你可以使用它的功能。在你的情况下,使用today.getHours()并检查它是否>= 12< 21以显示打开的邮件。关闭的消息可以出现在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.

请注意,这会使用客户端的时间,因此如果您在全球网页上使用它,那么您可能会在欧洲打开但同时在美国关闭。

回答by Andrew Rhyne

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

我不确定我的“时间逻辑”是否正确(检查 if 语句),但这应该是您要找的。

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

回答by Ruchi

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:

使用以下条件比较您的 var h 并获得所需的结果:

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

回答by Samuele Mattiuzzo

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

我通常使用这种解决方案,我发布只是为了获取知识(pimvdb 的回答确实更清楚)

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 comparison 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 comparison easier (thus not so much readable and mantainable)

您基本上将时间转换为整数,使比较更容易(因此可读性和可维护性不那么强)