view iso8601.js @ 13:447db2e8c622

Better access mode handling.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Wed, 08 Sep 2010 12:04:14 +0200
parents 9ee956af41e3
children 7cfcd7d5796c
line wrap: on
line source

/*
 * Thanks to Paul Sowden for this script.
 * http://delete.me.uk/2005/03/iso8601.html
 */

Date.prototype.setISO8601 = function(dString){
	var d;
	var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;
	if ((d = dString.match(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;
};

Date.prototype.toString = function (format, offset) {
	/* accepted values for the format [1-6]:
	 1 Year:
	   YYYY (eg 1997)
	 2 Year and month:
	   YYYY-MM (eg 1997-07)
	 3 Complete date:
	   YYYY-MM-DD (eg 1997-07-16)
	 4 Complete date plus hours and minutes:
	   YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
	 5 Complete date plus hours, minutes and seconds:
	   YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
	 6 Complete date plus hours, minutes, seconds and a decimal
	   fraction of a second
	   YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
	 */
	if (!format)
		var format = 5;
	if (!offset) {
		var offset = 'Z';
		var date = this;
	} else {
		var d = offset.match(/([-+])([0-9]{2}):([0-9]{2})/);
		var offsetnum = (Number(d[2]) * 60) + Number(d[3]);
		offsetnum *= ((d[1] == '-') ? -1 : 1);
		var date = new Date(Number(Number(this) + (offsetnum * 60000)));
	}

	var zeropad = function (num) { return ((num < 10) ? '0' : '') + num; };

	var str = "";
	str += date.getUTCFullYear();
	if (format > 1)
		str += "-" + zeropad(date.getUTCMonth() + 1);
	if (format > 2)
		str += "-" + zeropad(date.getUTCDate());
	if (format > 3)
		str += "T" + zeropad(date.getUTCHours()) +
			":" + zeropad(date.getUTCMinutes());
	if (format > 5) {
		var secs = Number(date.getUTCSeconds() + "." +
				((date.getUTCMilliseconds() < 100) ? '0' : '') +
				zeropad(date.getUTCMilliseconds()));
		str += ":" + zeropad(secs);
	} else if (format > 4)
		str += ":" + zeropad(date.getUTCSeconds());

	if (format > 3)
		str += offset;
	return str;
};