Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript date parsing on Iphone

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?

like image 631
Morten Avatar asked Mar 16 '11 10:03

Morten


People also ask

What does parsing date mean?

Definition and Usage parse() parses a date string and returns the time difference since January 1, 1970. parse() returns the time difference in milliseconds.

How are dates stored in JavaScript?

JavaScript stores dates as number of milliseconds since January 01, 1970. Zero time is January 01, 1970 00:00:00 UTC. One day (24 hours) is 86 400 000 milliseconds.

What is new date () in JavaScript?

new Date() exhibits legacy undesirable, inconsistent behavior with two-digit year values; specifically, when a new Date() call is given a two-digit year value, that year value does not get treated as a literal year and used as-is but instead gets interpreted as a relative offset — in some cases as an offset from the ...


1 Answers

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 the Date constructor:

var arr = "2010-03-15 10:30:00".split(/[- :]/),     date = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);  console.log(date); //-> Mon Mar 15 2010 10:30:00 GMT+0000 (GMT Standard Time) 

This will work the same in all browsers.

like image 121
Andy E Avatar answered Sep 17 '22 03:09

Andy E