JS Date object and iOS Safari

Safari on iOS is probably one of the best mobile browsers. Still there is one thing that I often got wrong and wonder why my webapp doesn’t work.

Javascript Date Object in iOS Safari

In every normal browser you could just create a Date object from string as

var myDate = new Date('2013-01-21T13:46:20');

But on iOS this simply gives you a JS error.

To fix it you should use the good ol’ split() and do something like this

//First we split the date string
var iosDateArr = '2013-01-21T13:46:20'.split('[- :T]');
//And use the constructor with 6 args
cDate = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);

Note that the Month in the array is reduced by one. This is because the Months are counted from 0 for January to 11 for December.


3 responses to “JS Date object and iOS Safari”

  1. Excellent 🙂 thank you
    Nothing about the subject anywere except your site. I tryed google and nothing from stack overflow too

  2. One small typo: .split(‘[- :T]’); needs to be .split(/[-:T]/) for JS. But other than that, huge thanks! Every time I scheduled a notification using new Date(string), my phonegap app would crash on an iphone (but not an ipod running the same OS version). Traced it back to the Date object so hopefully this works.

  3. Hey William,

    The .split() actually works also with a sting listing all the separators. In your case you use a regex which also works 🙂 so both are fine.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.