Every now and then, you run into a bug that is better described as a ‘pain in the ass’. This is one of these bugs, and it has to do with handling dates in iOS.

The story starts with the API of the Dutch Railways (or NS). They have a decent API in place and return dates in following format:

2015-05-18T15:02:00+0200
  

At first sight, it’s just a simple date string. Parsing this date in a desktop, Android or Windows Phone browser works like a charm. Sadly, on iOS, it doesn’t. It turns out to be the T right in the middle that causes the issues in iOS. So, my first guess was to remove that T with a simple regex.

var departureTime = advies.ActueleVertrekTijd,
      departureTimeRegex = vertrekTijd.replace(new RegExp("\\T","g"),' ');
  

This returns the date string as follows:

2015-05-18 15:02:00+0200
  

Sadly, iOS doesn’t like this one eather. After some online searches, the best solution seemed to be converting this string into an array:

var departureTime = advies.ActueleVertrekTijd,
      departureTimeRegex = departureTime.replace(new RegExp("\\T","g"),' '),
      departureTimeArray = departureTimeRegex.split(/[- :]/);
  

The array that we have now:

["2015", "05", "18", "15", "02", "00+0200"]
  

Finally, you’ll need to create a date object using this array:

var departureTime = advies.ActueleVertrekTijd,
      departureTimeRegex = departureTime.replace(new RegExp("\\T","g"),' '),
      departureTimeArray = departureTimeRegex.split(/[- :]/),
      departureTimeNew = new Date(departureTimeArray[0], departureTimeArray[1]-1, departureTimeArray[2], departureTimeArray[3], departureTimeArray[4]);
  

Et voila, we have a date object that works on iOS (and all other operating systems and browsers):

Mon May 18 2015 15:02:00 GMT+0200 (W. Europe Daylight Time)
  

It’s still unclear to me what causes this T-date bug, but at least there is a fix. If you have any thoughts on this, please comment below.

As a bonus, here’s the final code for handling T-dates wrapped in a function:

function returnDateObject(date){
    var dt = date,
      dtr = dt.replace(new RegExp("\\T","g"),' '),
      dta = dtr.split(/[- :]/),
      dtn = new Date(dta[0], dta[1]-1, dta[2], dta[3], dta[4]);
    return dtn;
  }
  

Leave a Reply