Get time difference between two dates in seconds

+1 vote
84 views
asked Dec 15, 2012 in java script by kalpana (3,995 points)

 

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 :)

1 Answer

0 votes
answered Jan 16, 2013 by admin (8,115 points)

This code snippet may be solved your problem

 

function get_time_difference(earlierDate,laterDate)
{
       var nTotalDiff = laterDate.getTime() - earlierDate.getTime();
       var oDiff = new Object();
 
       oDiff.days = Math.floor(nTotalDiff/1000/60/60/24);
       nTotalDiff -= oDiff.days*1000*60*60*24;
 
       oDiff.hours = Math.floor(nTotalDiff/1000/60/60);
       nTotalDiff -= oDiff.hours*1000*60*60;
 
       oDiff.minutes = Math.floor(nTotalDiff/1000/60);
       nTotalDiff -= oDiff.minutes*1000*60;
 
       oDiff.seconds = Math.floor(nTotalDiff/1000);
 
       return oDiff;
 
}
...