Javascript 比较时间不起作用

Javascript Comparing Time not working

本文关键字:不起作用 时间 比较 Javascript      更新时间:2023-09-26

>我正在尝试检查特定的ISO日期时间是否在18:00之前

这是简单的代码:

   // Define the date I want to check
    var targetDate = "2015-02-04T13:30:00Z";
    // Parse the string into a date object
    var target = new Date.parse(targetDate);
    // Compare the target date againt a new date object set to 18:00:00
    if(target < new Date().setHours(18 , 0, 0)){
        console.log("BEFORE");
    } else {
        console.log("AFTER");
    }

即使我的目标日期中的时间设置为 13:30:00,输出也始终为 AFTER。

搜索了如何比较时间,从我找到的结果来看,像我所做的那样进行简单的比较应该有效。

如果有人能指出我做错了什么,我将不胜感激。

测试代码会给出以下错误:

Uncaught TypeError: function parse() { [native code] } is not a constructor

这是因为"新"关键字。删除此选项可解决您的问题:

// Define the date I want to check
var targetDate = "2015-02-04T19:30:00Z";
// Parse the string into a date object
var target = Date.parse(targetDate);
// Compare the target date againt a new date object set to 18:00:00
if (target < new Date().setHours(18, 0, 0)) {
  console.log("BEFORE");
} else {
  console.log("AFTER");
}

当您尝试解析目标数据时,您不必使用 new 关键字。

这是一个有效的JSFiddle;

代码:

 // Define the date I want to check
 var targetDate = "2015-02-04T13:30:00Z";
 // Parse the string into a date object
 var target = Date.parse(targetDate);
 // Compare the target date againt a new date object set to 18:00:00
 if (target < new Date().setHours(18, 0, 0)) {
     alert("BEFORE");
 } else {
     alert("AFTER");
 }

尝试:

var targetDate = new Date("2015-02-04T13:30:00Z");
var numHours = targetDate.getHours();
if (numHours < 18) {
  console.log("BEFORE");
} else {
  console.log("AFTER");
}

如果您可以依靠 ISO 格式并且不想将其转换为本地时间

您可以只查看小时子字符串。

var targetDate = "2015-02-04T13:30:00Z";
var isbefore18=targetDate.substring(11,13)-18<0;
isbefore18 /*  value: (Boolean) true */

David P给出了正确的答案。Date() 由日期部分和时间部分组成

new Date().setHours(18,0,0)

创建一个日期在今天 18:00,该日期将始终大于 2015 年 2 月 4 日 17:30,除非您有时间机器。

targetDate.getHours()

返回时间部分的小时值,听起来像是您要查找的时间。