简体   繁体   English

如何比较Javascript中的日期?

[英]How do I compare dates in Javascript?

I have the following situation: 我有以下情况:

I have a certain function that runs a loop and does stuff, and error conditions may make it exit that loop. 我有一个运行循环并执行操作的特定函数,错误条件可能会使其退出该循环。 I want to be able to check whether the loop is still running or not. 我希望能够检查循环是否仍在运行。

For this, i'm doing, for each loop run: 为此,我正在做,为每个循环运行:

LastTimeIDidTheLoop = new Date();

And in another function, which runs through SetInterval every 30 seconds, I want to do basically this: 在另一个每30秒运行一次SetInterval的函数中,我想基本上这样做:

if (LastTimeIDidTheLoop is more than 30 seconds ago) {
  alert("oops");
}

How do I do this? 我该怎么做呢?

Thanks! 谢谢!

JS date objects store milliseconds internally, subtracting them from each other works as expected: JS日期对象在内部存储毫秒,相互减去它们按预期工作:

var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000; 
if (diffSeconds > 30)
{
  // ...
}

what about: 关于什么:

newDate = new Date()
newDate.setSeconds(newDate.getSeconds()-30);
if (newDate > LastTimeIDidTheLoop) {
  alert("oops");
}

You can do like this: 你可以这样做:

var dateDiff = function(fromdate, todate) {
    var diff = todate - fromdate;
    return Math.floor(diff/1000);
}

then: 然后:

if (dateDiff(fromdate, todate) > 30){
    alert("oops");
}

Create a date object and use setSeconds(). 创建一个日期对象并使用setSeconds()。

controlDate = new Date();
controlDate.setSeconds(controlDate.getSeconds() + 30);

if (LastTimeIDidTheLoop > controlDate) {
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM