使用JavaScript根据星期几来更改邮件?

时间:2014-10-08 04:18:01

标签: javascript html datetime

我正在为网站添加功能,以根据食物卡车是否打开来更改消息。我成功地根据时间改变了消息,但是我在实施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>

2 个答案:

答案 0 :(得分:1)

似乎你想提出一个&#34;关闭&#34;在星期一到星期五的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时间这样做,这在任何地方都是一致的。

答案 1 :(得分:0)

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

所以你必须检查

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