简体   繁体   English

使用JavaScript根据星期几更改消息?

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

I am adding functionality to a website to change the message depending on if a food truck is open. 我正在向网站添加功能,以根据是否打开餐车来更改消息。 I was successfully able to make the message change depending on the time, but I'm having trouble implementing getDay() to show the closed message all day on Saturday and Sunday. 我可以成功地根据时间更改消息,但是我无法实现getDay()以在星期六和星期日全天显示关闭的消息。

Here is the working script that I have so far: 这是我到目前为止的工作脚本:

 <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>

It seems you want to put up a "closed" message outside the hours of 11:00 to 14:00 Monday to Friday, so perhaps: 似乎您想在周一至周五的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;
}

Note however that if the date object is created on the client, it will be local to that timezone, which may not match wherever the shop is. 但是请注意,如果在客户端上创建了日期对象,则该日期对象将位于该时区本地,而无论商店在哪里,该时区都可能不匹配。 So you probably need to do this based on UTC time, which will be consistent everywhere. 因此,您可能需要根据UTC时间执行此操作,该时间在所有地方都将保持一致。

Use getDay() method to get the weekday from date object. 使用getDay()方法从日期对象获取工作日。 It returns a number from 0 - 6 to indicate days from sunday - saturday. 它返回从0到6的数字,以指示从星期日至星期六的日期。

So you have to check like 所以你必须检查像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM