I’m have a startDate and a endDate stored in a SQLite database and need to calculate the difference in minutes and seconds between the 2 datetimes using javascript.
For example:
startDate = 2012-10-07 11:01:13
endDate = 2012-10-07 12:42:13
I’ve had a good read though loads of similar questions on SO but could only find things relating to calculating this as part of a select.
All the answers are generally correct with respect to converting the dates to milliseconds in epoch time, subtracting those, and converting the result back from milliseconds into your required units (although the specific implementations offered elsewhere do not currently give you exactly what you asked for — i.e., just the number of minutes and seconds between your two datetimes).
However, please also note…
… that this is not a reliable way to construct the Date from your SQLite date strings.
When you feed a string into the constructor of a Date object, you are effectively calling
Date.parse(). That behaves differently on different browsers.Check this out:
Looks pretty good, right? But that’s on Chrome.
Now check out what happens in an up-to-date version of Firefox, with the exact same calls:
Furthermore, look at this behavior, in both browsers:
Simply prepending zeroes to the month and date digits causes a time warp! You have to set the time and a timezone (for me, PST) to make that go away:
Basically, dealing with date string parsing is a headache. You don’t want to have to digest and account for specs like this, this, and this.
So, here’s a better alternative — pass the parts of your datetime as separate args to the constructor of the Date object. That will reliably create the date for you, so your subsequent comparisons are valid.
Here’s what that initialization could look like for your case:
Note: be careful of timezone considerations. You don’t seem to have any timezone data in that SQLite format snippet.
Update
@james-j clarified that he’s looking for minutes and seconds specifically.
Here’s a snippet to extract just minutes and seconds: