comparison iso8601.js @ 0:9ee956af41e3

Initial commit
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Sun, 27 Jun 2010 22:05:12 +0200
parents
children 7cfcd7d5796c
comparison
equal deleted inserted replaced
-1:000000000000 0:9ee956af41e3
1 /*
2 * Thanks to Paul Sowden for this script.
3 * http://delete.me.uk/2005/03/iso8601.html
4 */
5
6 Date.prototype.setISO8601 = function(dString){
7 var d;
8 var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;
9 if ((d = dString.match(regexp))) {
10 var offset = 0;
11 this.setUTCDate(1);
12 this.setUTCFullYear(parseInt(d[1],10));
13 this.setUTCMonth(parseInt(d[3],10) - 1);
14 this.setUTCDate(parseInt(d[5],10));
15 this.setUTCHours(parseInt(d[7],10));
16 this.setUTCMinutes(parseInt(d[9],10));
17 this.setUTCSeconds(parseInt(d[11],10));
18 if (d[12])
19 this.setUTCMilliseconds(parseFloat(d[12]) * 1000);
20 else
21 this.setUTCMilliseconds(0);
22 if (d[13] != 'Z') {
23 offset = (d[15] * 60) + parseInt(d[17],10);
24 offset *= ((d[14] == '-') ? -1 : 1);
25 this.setTime(this.getTime() - offset * 60 * 1000);
26 }
27 } else
28 this.setTime(Date.parse(dString));
29 return this;
30 };
31
32 Date.prototype.toString = function (format, offset) {
33 /* accepted values for the format [1-6]:
34 1 Year:
35 YYYY (eg 1997)
36 2 Year and month:
37 YYYY-MM (eg 1997-07)
38 3 Complete date:
39 YYYY-MM-DD (eg 1997-07-16)
40 4 Complete date plus hours and minutes:
41 YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
42 5 Complete date plus hours, minutes and seconds:
43 YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
44 6 Complete date plus hours, minutes, seconds and a decimal
45 fraction of a second
46 YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
47 */
48 if (!format)
49 var format = 5;
50 if (!offset) {
51 var offset = 'Z';
52 var date = this;
53 } else {
54 var d = offset.match(/([-+])([0-9]{2}):([0-9]{2})/);
55 var offsetnum = (Number(d[2]) * 60) + Number(d[3]);
56 offsetnum *= ((d[1] == '-') ? -1 : 1);
57 var date = new Date(Number(Number(this) + (offsetnum * 60000)));
58 }
59
60 var zeropad = function (num) { return ((num < 10) ? '0' : '') + num; };
61
62 var str = "";
63 str += date.getUTCFullYear();
64 if (format > 1)
65 str += "-" + zeropad(date.getUTCMonth() + 1);
66 if (format > 2)
67 str += "-" + zeropad(date.getUTCDate());
68 if (format > 3)
69 str += "T" + zeropad(date.getUTCHours()) +
70 ":" + zeropad(date.getUTCMinutes());
71 if (format > 5) {
72 var secs = Number(date.getUTCSeconds() + "." +
73 ((date.getUTCMilliseconds() < 100) ? '0' : '') +
74 zeropad(date.getUTCMilliseconds()));
75 str += ":" + zeropad(secs);
76 } else if (format > 4)
77 str += ":" + zeropad(date.getUTCSeconds());
78
79 if (format > 3)
80 str += offset;
81 return str;
82 };