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 :)
time difference between now and 10 minutes later using momentjs
You can use
new Date().getTime()
for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which isms
intos
.Below code will give the time difference in second.
The Code
Or even simpler
(endDate - startDate) / 1000
as pointed out in the comments unless you're using typescript.The explanation
You need to call the
getTime()
method for theDate
objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling thegetDate()
method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling thegetTime()
method, representing the number of milliseconds since January 1st 1970, 00:00Rant
Depending on what your date related operations are, you might want to invest in integrating a library such as date.js or moment.js which make things so much easier for the developer, but that's just a matter of personal preference.
For example in moment.js we would do
moment1.diff(moment2, "seconds")
which is beautiful.Useful docs for this answer
try using dedicated functions from high level programming languages. JavaScript
.getSeconds();
suits here: