I'm passing a date from Ruby to Javascript via JSON.
It comes into Javascript as "2010-03-24T10:00:00Z".
Now, how the heck do I format that in Javascript?
I'm passing a date from Ruby to Javascript via JSON.
It comes into Javascript as "2010-03-24T10:00:00Z".
Now, how the heck do I format that in Javascript?
I suppose I'd do it kinda like this to construct a date object first:
function dp(dateStr) {
var pattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/;
var match = pattern.exec(dateStr);
if (!match) {throw new Error('::Error, #dp could not parse dateStr '+dateStr);}
// we're safe to use the fields
return new Date(match[1], match[2]-1, match[3], match[4], match[5], match[6]);
}
console.log(dp('2010-03-24T10:00:00Z'));
Then I could pretty-print it in different ways. See how the month (field with idx 2 in the match array) needs to be fiddled with due to zero-index (as opposed to the date field).
According to the EcmaScript 5 spec, JSON dates should be encoded as ISO strings. This is how toJSON
of JavaScript date objects could look like:
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
Fortunately Ruby seems to encode dates the same way. An elegant solution is to provide a reviver function to the JSON parse function, which converts ISO date strings into Date objects:
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
}
}
return value;
});
This should work with all standard compliant JSON implementations.
Both samples are taken from the json2 source code by Douglas Crockford.