I'm working on an offline capabable Javascript site that targets mobile devices. One such mobile device is the IPhone.
I'm trying to parse a date from our REST API (a member of JSON object). I'm using
Date.parse("2010-03-15 10:30:00");
This works on Android devices, however on IPhone it just gives an invalid date.
How do I need to format my date string so it can be parsed by the IPhone?
Not all browsers support the same date formats. The best approach is to split the string on the separator characters (
and
-
,:
) instead, and pass each of the resulting array items to theDate
constructor:This will work the same in all browsers.
You might have better luck if you stick to ISO 8601 format:
For UTC/GMT time, you can try:
The date object will display in the proper local timezone when used.
If you can correct your REST API to send down proper ISO 8601 date times, the proper way to handle this is to use a regex shim that allows all browsers to process ISO 8601 dates. Sure it might be slower, but handling dates with Javascript is like trying to get a cat into a tub of water.
Keep in mind the following method overrides the original Date.parse method. This could be problematic in larger projects or with many developers with different expectations. Use only if you're aware of what you're doing.
https://github.com/csnover/js-iso8601