Get time difference between two dates in seconds

I’m trying to get a difference between two dates in seconds. The logic would be like this :

  • set an initial date which would be now;
  • set a final date which would be the initial date plus some amount of seconds in future ( let’s say 15 for instance )
  • get the difference between those two ( the amount of seconds )

The reason why I’m doing it it with dates it’s because the final date / time depends on some other variables and it’s never the same ( it depends on how fast a user does something ) and I also store the initial date for other things.

I’ve been trying something like this :

var _initial = new Date(),
    _initial = _initial.setDate(_initial.getDate()),
    _final = new Date(_initial);
    _final = _final.setDate(_final.getDate() + 15 / 1000 * 60);

var dif = Math.round((_final - _initial) / (1000 * 60));

The thing is that I never get the right difference. I tried dividing by 24 * 60 which would leave me with the seconds, but I never get it right. So what is it wrong with my logic ? I might be making some stupid mistake as it’s quite late, but it bothers me that I cannot get it to work 🙂

9 Answers
9

Leave a Comment