JavaScript 时间比较

标签 javascript datetime time if-statement

我目前有以下脚本:

<script>
if(new Date().getHours() > 17 || (new Date().getHours() == 17 &&     
new Date().getMinutes()== 0 && new Date().getSeconds() == 0) && 
(new Date().getHours() < 21 && new Date().getMinutes() < 30 
&& new Date().getSeconds() == 0)){
        //do nothing.   
    } else {
    $(document).ready(function() {
        $(".inline").colorbox({inline:true, open:true, width:"50%"});
        });
    }

那么 if 中的基本含义是: 如果时间是 17:00 到 21:30,则不执行任何操作,否则显示该框。但发生的情况是,盒子在 18:00 左右停止工作,并在午夜再次开始工作。有人看到这里出了什么问题吗?

最佳答案

请注意,日期中的许多字段(包括小时)都是 0 索引的。这就是您观察到该服务在 18:00 左右停止工作的原因。

我建议使用变量来使条件更易于推理。尝试这样的事情。如果您担心 namespace 污染,请在它周围放置一个闭包。

var now = new Date();
var startQuietPeriod = new Date();
startQuietPeriod.setHours(16); startQuietPeriod.setMinutes(0); startQuietPeriod.setSeconds(0); startQuietPeriod.setMilliseconds(0);  // Today at 17:00
var endQuietPeriod = new Date();
endQuietPeriod.setHours(20); endQuietPeriod.setMinutes(30); endQuietPeriod.setSeconds(0); endQuietPeriod.setMilliseconds(0);  // Today at 21:30
if (startQuietPeriod < now && now < endQuietPeriod) {
  // don't show prompt
} else {
  // show prompt
}

关于JavaScript 时间比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12552280/

相关文章:

javascript - 使用 jQuery 插件验证图像

javascript - 在 JS 单击上添加边框后,填充使元素移动

python - 报库中的发布日期总是返回无

c# - 解析时获取 DateTime 值的原始时区

time - 如何解释 RFC3339 UTC 时间戳

iphone - 如何在 iPhone 中设置倒计时?

javascript - city.statename.data 生成错误无法读取 Object.city 中未定义的属性 'data'

php - 将 PHP 中的日期时间字符串保存到 MySQL 中

c++ - 32 位 Linux clock() 溢出

javascript - 如何在 PHP 中将 JavaScript 文字对象转换为 Json 对象