如何根据一天中的时间更改消息

How do I change a message based on the time of the day?

本文关键字:时间 消息 何根 一天      更新时间:2023-09-26

我想根据一天中的时间更改内容,这说明我的商家是营业还是停业。我使用以下Javascript:

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
    var dt = new Date();
    var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
    enter code here
    if (day <= 0) {
        if (time < "11:00:00") {
            document.write('Good morning! We are currently closed, you can reach us at 11 AM')
        } else if (time > "16:30:00" && time < "18:00:00") {
            document.write('Good afternoon! We are currently closed. You can reach us tomorrow')
        } else if (time > "18:00:00") {
            document.write('Good evening! We are currently closed. You can reach us tomorrow')
        } else {
            document.write('Customer service: &nbsp;&nbsp; <i class="fa fa-phone"></i> &nbsp;+1 555.234.987')
        }
    } else if (day <= 1) {
        if (time < "09:00:00") {
            document.write('Good morning! We are currently closed, you can reach us at 9 AM')
        } else if (time > "19:00:00") {
            document.write('Good evening! We are currently closed, you can reach us tomorrow')
        } else {
            document.write('Customer Service: &nbsp;&nbsp; <i class="fa fa-phone"></i> &nbsp;+1 555.234.987')
        }
    } 
</script>

从周一到周日以此类推。

由于某种原因,文本显示另一个文本,因此当星期一上午 10 点时,文本显示"晚上好!我们目前关闭,您明天可以联系我们">

我知道我做错了什么,但我不知道是什么...

你不能像这样比较字符串。

用:

$hour = dt.getHours();

然后:

if ($hour > 10) {
 ..
}

等。

我认为

这是因为您尝试在字符串而不是数字上制作...

尝试使用 if 只使用 dt.getHours((:

if (dt.getHours() < 11) {
document.write('Good morning! We are currently closed, you can reach us at 11 AM')
}

使用以下元素:

首先获取日期,小时和分钟

var dt = new Date();
var day = dt.getDay();
var hour = dt.getHours();
var minute= dt.getMinutes();

切换日期:

switch(day) {
    case 0:
        //Be carefull! This is Sunday!
        break;
    case 1:
        //Monday
        break;
    case 2:
        //Thuesday
        break;
} 

在比较时代的情况下:

    case 1:
    if (hour < 11) {
        document.write('Good morning! We are currently closed, you can reach us at 11 AM')
    } else if (((hour >= 16 && minutes >= 30) || hour >= 17) && hour < 18) {
        document.write('Good afternoon! We are currently closed. You can reach us tomorrow')
    } else if (hour >= 18) {
        document.write('Good evening! We are currently closed. You can reach us tomorrow')
    } else {
        document.write('Customer service: &nbsp;&nbsp; <i class="fa fa-phone"></i> &nbsp;+1 555.234.987')
    }
        break;

其余的应该很容易复制粘贴:)