使用JavaScript根据一周中的哪一天更改消息

Using JavaScript to change a message depending on the day of the week?

本文关键字:一天 消息 JavaScript 一周 使用      更新时间:2023-09-26

我正在向网站添加功能,以根据食品车是否打开来更改消息。我成功地根据时间更改了消息,但在实现getDay()以在周六和周日全天显示关闭消息时遇到了问题。

这是我目前为止的工作脚本:

 <script language="JavaScript">
        var mess1="";
        var outmess= "Kendo's Cuisine "
        document.write("<center><font size=+1><i><b>")
        day = new Date( )
        hr = day.getHours( )
        if (( hr >= 0 ) && (hr <= 11 ))
        mess1= "is closed right now. He's open Mon - Fri 11am - 2pm. "
        if (( hr >= 11 ) && (hr < 13))
        mess1=" is open right now! Call in your order to have it ready by the time you get here!"
        if (( hr >= 13) && (hr <= 14))
        mess1= "usually runs out of food by now! Call before you come!"
        if (( hr >= 14 ) && (hr <= 24 ))
        mess1= "is closed right now. He's open Mon - Fri 11am - 2pm. "
        document.write("<blink>")
        document.write(outmess)
        document.write("</blink>")
        document.write(mess1)
        document.write("</b></i></font></center>")
      </script>

您似乎想在周一至周五11:00至14:00的时间之外发布一条"关闭"消息,所以可能:

function isOpen(date) {
  var day = date.getDay();
  var hour = date.getHours();
  if (day == 0 || day == 6 || hour < 11 || hour > 13) {
    // shop is closed
    return false;
  }
  // Otherwise, the shop is open
  return true;
}

但是请注意,如果日期对象是在客户端上创建的,那么它将是该时区的本地时区,无论商店在哪里,它都可能不匹配。因此,您可能需要根据UTC时间来执行此操作,因为UTC时间在任何地方都是一致的。

使用getDay()方法从日期对象获取工作日。它返回一个从0到6的数字,表示周日到周六的天数。

所以你必须像一样检查

var day = new Date();
if(day.getDay() == 0 || day.getDay() == 6) {
   alert("shop is closed");
}