JavaScript new Date() NaN on iPhone

This is one of those problems that in reflection is rather simple but at the time is very very (very!) annoying.

Background

I’m writing an application that synchronizes data to and from a mobile device and the application has a display that will tell you how long since you last synced. The application gives back the correct information on my Android device but on an iPhone I used for development ( well the wife’s phone , don’t want to admit to owning one :), that’s a  joke for you hardcore apple lovers, I was getting NaN (not a number).

Why the Problem ?

I’m getting the issues and other’s out there may also be for the same reason. I am passing a string to the Date object and is in the following format ;

yyyy-mm-dd hh:mm:ss

It turns out that The yyyy-mm-dd (ISO 8601) date format is not supported in Safari and IE. It is part of ECMAscript 5.

I wasn’t sure how to reproduce the issue at first as it was happening on the iPhone but realizing it may be rendering in Safari I downloaded the safari web browser to my windows machine.’

Example of Date Problem

Safari: Calling new date in Safari with the format I use in my application.

safari_newdate_err

Chrome: Exactly the same code and a Date object is created.

chrome_newdate
Getting around the problem

To get around the issue I check on the mobile if its running on a Apple product and then I simply reformat the date so it creates a new Date object in the following format ;

mm/dd/yyyy hh:mm:ss

Safari: new Date with altered format.

safari_newdate

I have used Phonegaps standard application object and added a function that checks for the device

var app = {

isAppleDevice: function() {
    if (navigator.userAgent.match(/(iPhone|iPod|iPad)/) != null) {
      return true;
    }
    return false;
  },.....etc

Then I can simple determine that when the application is running on iPhone/iPad I can alter the date (assuming myDate variable is in format mentioned at start of the post).

if (app.isAppleDevice()) {
var dateParts = myDate.substring(0,10).split('-');
var timePart = myDate.substr(11);
myDate= dateParts[1] + '/' + dateParts[2] + '/' + dateParts[0] + ' ' + timePart;
}

Hope that helps someone. I found a useful date library in my searches for the answer but the simplest solution was the one in my post :).

Hope that Helps

Thanks for reading.

Neil

Advertisements

One thought on “JavaScript new Date() NaN on iPhone

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s