javascript 比较javascript中的时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46478974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:41:46  来源:igfitidea点击:

compare timestamps in javascript

javascripttimestamp

提问by Sredny M Casanova

I have a date saved in a string with this format: 2017-09-28T22:59:02.448804522Zthis value is provided by a backend service.

我有一个以这种格式保存在字符串中的日期:2017-09-28T22:59:02.448804522Z该值由后端服务提供。

Now, in javascript how can I compare if that timestamp is greater than the current timestamp? I mean, I need to know if that time happened or not yet taking in count the hours and minutes, not only the date.

现在,在 javascript 中如何比较时间戳是否大于当前时间戳?我的意思是,我需要知道那个时间是否已经发生或尚未计算小时和分钟,而不仅仅是日期。

回答by nicooga

You can parse it to create an instance of Dateand use the built-in comparators:

您可以解析它以创建一个实例Date并使用内置比较器:

new Date('2017-09-28T22:59:02.448804522Z') > new Date()
// true
new Date('2017-09-28T22:59:02.448804522Z') < new Date()
// false

回答by agm1984

You could also convert it to unix time in milliseconds:

您还可以将其转换为以毫秒为单位的 unix 时间:

console.log(new Date('2017-09-28T22:59:02.448804522Z').valueOf())

const currentTime = new Date('2017-09-28T22:59:02.448804522Z').valueOf()
    
const expiryTime = new Date('2017-09-29T22:59:02.448804522Z').valueOf()

if (currentTime < expiryTime) {
    console.log('not expired')
}

回答by selmansamet

const anyTime = new Date("2017-09-28T22:59:02.448804522Z").getTime();
const currentTime = new Date().getTime();
if(currentTime > anyTime){
    //codes
}

回答by TinkerTenorSoftwareGuy

If you can, I would use moment.js * https://momentjs.com/

如果可以,我会使用 moment.js * https://momentjs.com/

You can create a moment, specifying the exact format of your string, such as:

您可以创建一个时刻,指定字符串的确切格式,例如:

var saveDate = moment("2010-01-01T05:06:07", moment.ISO_8601);

Then, if you want to know if the saveDateis in the past:

然后,如果您想知道saveDate过去是否为:

boolean isPast = (now.diff(saveDate) > 0);

boolean isPast = (now.diff(saveDate) > 0);

If you can't include an external library, you will have to string parse out the year, day, month, hours, etc - then do the math manually to convert to milliseconds. Then using Date object, you can get the milliseconds:

如果您不能包含外部库,则必须将年、日、月、小时等字符串解析出来 - 然后手动进行数学运算以转换​​为毫秒。然后使用 Date 对象,您可以获得毫秒:

var d = new Date();
var currentMilliseconds = d.getMilliseconds();

At that point you can compare your milliseconds to the currentMilliseconds. If currenMilliseconds is greater, then the saveDate was in the past.

此时,您可以将毫秒数与当前毫秒数进行比较。如果currenMilliseconds 更大,那么saveDate 是过去的。