如何准确比较时间和日期?

时间:2021-08-01 13:38:24

标签: javascript

我想检查给定的时间和日期是否还没有过去,所以我有这个:

var currentdate = new Date(); 
var currentTime = "Last Sync: " + currentdate.getDate() + "/"
                    + (currentdate.getMonth()+1)  + "/" 
                    + currentdate.getFullYear() + " @ "  
                    + currentdate.getHours() + ":"  
                    + currentdate.getMinutes() + ":" 
                    + currentdate.getSeconds();
    
    
const givenTime = '2021-08-01T16:49:08.678Z';
    
// This is not comparing time , it only compares the dates
console.log(new Date(givenTime) > new Date, currentTime);

不幸的是,代码似乎没有比较时间,只比较日期,所以同一天两次返回错误结果:

我的意思是代码返回 true 如果:const givenTime = '2021-08-01T16:49:08.678Z'; 并且当前日期是 " 1/8/2021 @ 18:7:21"

如何准确比较时间和日期?

4 个答案:

答案 0 :(得分:-1)

首先将这些 Date 对象转换为时间戳(数字),然后比较它们的相等性。

示例

var timestamp_1970 = new Date(0).getTime(); // 1970-01-01 00:00:00
var timestamp = new Date().getTime(); // Current Timestamp

答案 1 :(得分:-1)

您似乎正在尝试比较两个本地日期/时间。在这种情况下,请勿将其中之一指定为 UTC。

// delete the Z
const givenTime = '2021-08-01T16:49:08.678';

请注意,如果当前时间晚于您当地时区的下午 4:49,此代码段只会返回“false”。对我来说,它不是,所以我得到了“真实”。

此外,new Date(givenTime) > new Date 也不起作用。我相信您的意思是 new Date(givenTime) > new Date(currentdate)new Date(givenTime) > new Date() - 它们本质上是相同的。

var currentdate = new Date(); 
var currentTime = "Last Sync: " + currentdate.getDate() + "/"
                    + (currentdate.getMonth()+1)  + "/" 
                    + currentdate.getFullYear() + " @ "  
                    + currentdate.getHours() + ":"  
                    + currentdate.getMinutes() + ":" 
                    + currentdate.getSeconds();
    
    
const givenTime = '2021-08-01T16:49:08.678';
    
// This is not comparing time , it only compares the dates
console.log(new Date(givenTime) > new Date(currentdate), currentTime);

答案 2 :(得分:-1)

我刚刚使用了它,它在不触及给定时间的情况下完美运行:

var currentTime =  new Date().toISOString();

console.log(currentTime)

const givenTime = '2021-08-01T14:13:08.678Z';

console.log(givenTime > currentTime); 

答案 3 :(得分:-2)

比较两个日期的最简单方法是使用 UNIX timestamps

.getTime() 之后添加 const currentDate 会将日期对象转换为 UNIX 时间戳。 UNIX 时间戳很容易比较。 const givenTime = new Date('2021-08-01T16:49:08.678Z').getTime(); 还返回一个 UNIX 时间戳,然后您可以将其与当前时间进行比较。