Assuming the following UTC RFC 3339 timestamp:
2012-09-30 12:12:12Z
What is a good way of generating a localized Date
in JavaScript?
I've arrived at the following convoluted (but working) solution, and I cannot help but thinking that I have missed something.
/**
* Accepts a string on the format YYYY-MM-DD HH:MM:SS
* and returns a localised Date
*/
DateUtils.localised_date_from = function (rfc_timestamp) {
var date_parts = rfc_timestamp.substring(0, 10).split("-"),
time_parts = rfc_timestamp.substring(10).split(":"),
year = parseInt(date_parts[0], 10),
month = parseInt(date_parts[1], 10) - 1,
date = parseInt(date_parts[2], 10),
hours = parseInt(time_parts[0], 10),
minutes = parseInt(time_parts[1], 10),
seconds = parseInt(time_parts[2], 10),
utc_timestamp = Date.UTC(year, month, date, hours, minutes, seconds);
return new Date(utc_timestamp);
};
Edit:
Date.parse
ought to be a great starting point but simply does not work with RFC3339 in older browsers, at least not in IE8 where new Date(Date.parse("2012-09-30 12:12:12Z"))
returns NaN
.