我一直试图让这个脚本在一天的某些时段显示一个段落。现在我试图添加某些日子,比如周末。我无法弄明白。
这是我尝试过的十几件事之一:
var day = new Date();
var week = day.getHours();
var weekend = day.getDay() == 0 || day.getDay() == 6;
if (week < 4 || week > 12) || (weekend === true) { document.write('<p class="alert alert-danger department-hours-warning"><i class="fa fa-clock-o fa-3x pull-left"></i>NOTICE: This is not a 24 hour department and we are currently closed, please anticipate a delay in response. Our department hours are from 09:00-17:00 EST Monday through Friday. We are closed on USA holidays and other days that may be listed on our calendar.</p>'); }
如果工作日凌晨4点到12点之间没有显示段落,那么此处的目标也是如此。
编辑:更新的脚本,但它无法正常工作。
答案 0 :(得分:1)
正如您之前提出的问题(自删除以来)中所述。 JS日期非常棘手。例如,您的代码new Date()
是相对于用户本地时区创建的,而不是您的业务。这意味着对你来说这可能是一个工作日,而对我来说这是一个周末。
我的建议是使用像MomentJS这样的库来协助您的查询。它看起来像是:
(function(){
function initialize(){
moment.tz.setDefault('America/New_York'); // replace this with your actual timezone
var NOW = moment();
var alertZone = document.getElementById('alertZone');
// is weekend or out of office hours
if(NOW.isoWeekday() > 5 || NOW.hour() < 9 || NOW.hour() > 17){
alertZone.innerHTML = '<p class="alert alert-danger department-hours-warning clearfix"><i class="fa fa-clock-o fa-3x pull-left"></i>NOTICE: This is not a 24 hour department and we are currently closed, please anticipate a delay in response. Our department hours are from 09:00-17:00 EST Monday through Friday. We are closed on USA holidays and other days that may be listed on our calendar.</p>';
}else{
alertZone.innerHTML = '<p class="alert alert-success department-hours-success clearfix"><i class="fa fa-clock-o fa-3x pull-left"></i>Welcome y\'all we\'re open!</p>';
}
}
window.onload = initialize;
})()
&#13;
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.11/moment-timezone.min.js"></script>
<div id="alertZone"></div>
&#13;
<强>解释强>
Moment timezone让我们使用.setDefault()
设置您的本地时区(此后创建的所有时刻将相对于您的时区而非用户的时区)。
然后我们使用.isoWeekday()
(这是一周中某一天的非特定区域检查[1-5 =周一 - 周五])和.hour()
(返回0-之间的数字)进行检查23)如果我们不在办公时间。