最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I compare dates in Javascript? - Stack Overflow

programmeradmin3浏览0评论

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:

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

How do I do this?

Thanks!

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:

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

How do I do this?

Thanks!

Share Improve this question asked Dec 7, 2008 at 21:40 Daniel MagliolaDaniel Magliola 32.4k63 gold badges174 silver badges246 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

JS date objects store milliseconds internally, subtracting them from each other works as expected:

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().

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

if (LastTimeIDidTheLoop > controlDate) {
...
发布评论

评论列表(0)

  1. 暂无评论