You can not rely on Date
to parse a string correctly (here is a comparison and that's before the introduction of ISO8601 parsing - ECMA5) into a Date
object, so for cross browser it is best to do it yourself. You also can not rely on the string returned from Date.toString()
and again for cross browser you will need to format it yourself, or use a library like moments.js. It's that simple.
The string you have is a date stamp in ISO8601 format and specifically, by the ISO8601 specification, is assumed to be local time as no offset is supplied, I am going to assume it is UTC. Many browsers and libraries, the W3C and the ECMA5 spec (that have errata that change the assumption) disagree on this, and you can not take it for granted that local time is assumed.
You obviously have a browser that supports these strings. But when you output Date.toString
you are asking for the local time (as per your environment), but you want UTC (assumed) and so you need Date.toUTCString()
, but these methods are implementation dependant and you may not get the same string in different environments.
Javascript
function parseMyDateString(str) {
var parts = str.split(/[-T:]/);
parts[1] -= 1;
return new Date(Date.UTC.apply(undefined, parts));
}
function padLeft(arg) {
var str = String(arg);
if (str.length < 2) {
str = '0' + str;
}
return str;
}
function formatMyDateString(date) {
var days = [
'Sun',
'Mon',
'Tue',
'Wed',
'Thu',
'Fri',
'Sat'
],
months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
],
dateString = [
days[date.getUTCDay()],
months[date.getUTCMonth()],
padLeft(date.getUTCDate()),
date.getUTCFullYear()
].join(' '),
timeString = [
padLeft(date.getUTCHours()),
padLeft(date.getUTCMinutes()),
padLeft(date.getUTCSeconds())
].join(':');
return [
dateString,
timeString,
'GMT'
].join(' ');
}
var iso8601String = '2014-02-02T20:10:00',
dateObject = parseMyDateString(iso8601String),
myDateString = formatMyDateString(dateObject);
console.log(myDateString);
Output
Sun Feb 02 2014 20:10:00 GMT
On jsFiddle