1

So I want to calculate the difference between two date objects that are created using a string, like this:

var difference = new Date("2014-10-13 23:57:52") - new Date("2014-10-13 20:30:00");

This works perfectly on a desktop, but on iProducts and on Blackberry (mobile chrome, safari and blackberry browser), it returns NaN -- I haven't tested yet on an Android --. I've realised that these mobile browsers can't handle anything that isn't like the default format given by new Date();. Is there a way that I could calculate the difference? I reckon I could try to parse my custom dates into the default one, but if there's a simpler solution, it would be very appreciated! Thanks!

EDIT: I've made it work by changing the date format to new Date("2014-10-13T23:57:52Z");. To do this programatically, I've done this:

var difference = (new Date(date1.concat('Z').replace(/\s/, 'T')) - new Date(date2.concat('Z').replace(/\s/, 'T'))) / 1000 / 60;

I use .concat('Z') to add the 'Z' character at the end, then I use a regex to replace the white space by a 'T'. I divide everything by 1000, then 60, to give me the results in minutes.

jonathanGB
  • 1,500
  • 2
  • 16
  • 28
  • Might have something to do with the ill–advised parsing of strings with the Date constructor. It does not "work perfectly" in desktop browsers if you attempt it in IE 8, or compare the resulting date object in Chrome and Firefox or Safari (which both think it's an invalid date). – RobG Oct 14 '14 at 02:13
  • Try it in IE8 (or similar). – RobG Oct 14 '14 at 05:26

0 Answers0