ISO Date Time

Useful JavaScript for converting an iso DateTime string into a JavaScript Date object. The Date.prototype.setISO8601 function is from dansnetwork.com/javascript-iso8601rfc3339-date-parser/

Fiddle with this

function isoToDateTime(value) {
	var output = '';
	if (value != '0001-01-01T00:00:00') {
		var d = new Date();
		d.setISO8601(value);
		//desired output format: 5/17/2011 8:34:56 AM - below does not return local time
		output = d.getMonth() + 1 + "/" + d.getDate() + "/" + d.getFullYear() + " " + setClockTime(d)
	}
	return output;
}

function setClockTime(d)
{
	var h = d.getHours();
	var m = d.getMinutes();
	var s = d.getSeconds();
	var suffix = "AM";
	if (h > 11) {suffix = "PM";}
	if (h > 12) {h = h - 12;}
	if (h == 0) {h = 12;}
	if (h < 10) {h = "0" + h;}
	if (m < 10) {m = "0" + m;}
	if (s < 10) {s = "0" + s;}
	return h + ":" + m + ":" + s + " " + suffix;
}

//convert an ISO8601 date string into a js date object
Date.prototype.setISO8601 = function(dString){
var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;
if (dString.toString().match(new RegExp(regexp))) {
	var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;
	if (dString.toString().match(new RegExp(regexp))) {
		var d = dString.match(new RegExp(regexp));
		var offset = 0;
		this.setUTCDate(1);
		this.setUTCFullYear(parseInt(d[1],10));
		this.setUTCMonth(parseInt(d[3],10) - 1);
		this.setUTCDate(parseInt(d[5],10));
		this.setUTCHours(parseInt(d[7],10));
		this.setUTCMinutes(parseInt(d[9],10));
		this.setUTCSeconds(parseInt(d[11],10));
		if (d[12]) {
			this.setUTCMilliseconds(parseFloat(d[12]) * 1000);
		}
		else {
			this.setUTCMilliseconds(0);
		}
		if (d[13] != 'Z') {
			offset = (d[15] * 60) + parseInt(d[17],10);
			offset *= ((d[14] == '-') ? -1 : 1);
			this.setTime(this.getTime() - offset * 60 * 1000);
		}
	}
	else {
		this.setTime(Date.parse(dString));
	}
		return this;
	}
}
comments powered by Disqus