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

时间:2014-12-04 11:39:23

标签: javascript jquery date time

我想根据一天中的时间更改内容,这会告诉我的业务是开放还是已关闭。我使用以下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点时,文字显示“晚上好!我们现在关闭,你明天可以联系到我们”

我知道我做错了什么,但我无法弄清楚是什么......

3 个答案:

答案 0 :(得分:0)

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

使用:

$hour = dt.getHours();

然后:

if ($hour > 10) {
 ..
}

答案 1 :(得分:0)

我认为它是因为你试图在String而不是Numers ...

尝试仅使用dt.getHours():

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

答案 2 :(得分:0)

使用以下元素:

首先得到日,小时和分钟

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;

休息应该很容易复制粘贴:)