Date.js
[roojs1] / Date.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12 /**
13  * @class Date
14  *
15  * The date parsing and format syntax is a subset of
16  * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
17  * supported will provide results equivalent to their PHP versions.
18  *
19  * Following is the list of all currently supported formats:
20  *<pre>
21 Sample date:
22 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
23
24 Format  Output      Description
25 ------  ----------  --------------------------------------------------------------
26   d      10         Day of the month, 2 digits with leading zeros
27   D      Wed        A textual representation of a day, three letters
28   j      10         Day of the month without leading zeros
29   l      Wednesday  A full textual representation of the day of the week
30   S      th         English ordinal day of month suffix, 2 chars (use with j)
31   w      3          Numeric representation of the day of the week
32   z      9          The julian date, or day of the year (0-365)
33   W      01         ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
34   F      January    A full textual representation of the month
35   m      01         Numeric representation of a month, with leading zeros
36   M      Jan        Month name abbreviation, three letters
37   n      1          Numeric representation of a month, without leading zeros
38   t      31         Number of days in the given month
39   L      0          Whether it's a leap year (1 if it is a leap year, else 0)
40   Y      2007       A full numeric representation of a year, 4 digits
41   y      07         A two digit representation of a year
42   a      pm         Lowercase Ante meridiem and Post meridiem
43   A      PM         Uppercase Ante meridiem and Post meridiem
44   g      3          12-hour format of an hour without leading zeros
45   G      15         24-hour format of an hour without leading zeros
46   h      03         12-hour format of an hour with leading zeros
47   H      15         24-hour format of an hour with leading zeros
48   i      05         Minutes with leading zeros
49   s      01         Seconds, with leading zeros
50   O      -0600      Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
51   P      -06:00     Difference to Greenwich time (GMT) with colon between hours and minutes
52   T      CST        Timezone setting of the machine running the code
53   Z      -21600     Timezone offset in seconds (negative if west of UTC, positive if east)
54 </pre>
55  *
56  * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
57  * <pre><code>
58 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
59 document.write(dt.format('Y-m-d'));                         //2007-01-10
60 document.write(dt.format('F j, Y, g:i a'));                 //January 10, 2007, 3:05 pm
61 document.write(dt.format('l, \\t\\he dS of F Y h:i:s A'));  //Wednesday, the 10th of January 2007 03:05:01 PM
62  </code></pre>
63  *
64  * Here are some standard date/time patterns that you might find helpful.  They
65  * are not part of the source of Date.js, but to use them you can simply copy this
66  * block of code into any script that is included after Date.js and they will also become
67  * globally available on the Date object.  Feel free to add or remove patterns as needed in your code.
68  * <pre><code>
69 Date.patterns = {
70     ISO8601Long:"Y-m-d H:i:s",
71     ISO8601Short:"Y-m-d",
72     ShortDate: "n/j/Y",
73     LongDate: "l, F d, Y",
74     FullDateTime: "l, F d, Y g:i:s A",
75     MonthDay: "F d",
76     ShortTime: "g:i A",
77     LongTime: "g:i:s A",
78     SortableDateTime: "Y-m-d\\TH:i:s",
79     UniversalSortableDateTime: "Y-m-d H:i:sO",
80     YearMonth: "F, Y"
81 };
82 </code></pre>
83  *
84  * Example usage:
85  * <pre><code>
86 var dt = new Date();
87 document.write(dt.format(Date.patterns.ShortDate));
88  </code></pre>
89  */
90
91 /*
92  * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
93  * They generate precompiled functions from date formats instead of parsing and
94  * processing the pattern every time you format a date.  These functions are available
95  * on every Date object (any javascript function).
96  *
97  * The original article and download are here:
98  * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
99  *
100  */
101  
102  
103  // was in core
104 /**
105  Returns the number of milliseconds between this date and date
106  @param {Date} date (optional) Defaults to now
107  @return {Number} The diff in milliseconds
108  @member Date getElapsed
109  */
110 Date.prototype.getElapsed = function(date) {
111         return Math.abs((date || new Date()).getTime()-this.getTime());
112 };
113 // was in date file..
114
115
116 // private
117 Date.parseFunctions = {count:0};
118 // private
119 Date.parseRegexes = [];
120 // private
121 Date.formatFunctions = {count:0};
122
123 // private
124 Date.prototype.dateFormat = function(format) {
125     if (Date.formatFunctions[format] == null) {
126         Date.createNewFormat(format);
127     }
128     var func = Date.formatFunctions[format];
129     return this[func]();
130 };
131
132
133 /**
134  * Formats a date given the supplied format string
135  * @param {String} format The format string
136  * @return {String} The formatted date
137  * @method
138  */
139 Date.prototype.format = Date.prototype.dateFormat;
140
141 // private
142 Date.createNewFormat = function(format) {
143     var funcName = "format" + Date.formatFunctions.count++;
144     Date.formatFunctions[format] = funcName;
145     var code = "Date.prototype." + funcName + " = function(){return ";
146     var special = false;
147     var ch = '';
148     for (var i = 0; i < format.length; ++i) {
149         ch = format.charAt(i);
150         if (!special && ch == "\\") {
151             special = true;
152         }
153         else if (special) {
154             special = false;
155             code += "'" + String.escape(ch) + "' + ";
156         }
157         else {
158             code += Date.getFormatCode(ch);
159         }
160     }
161     /** eval:var:zzzzzzzzzzzzz */
162     eval(code.substring(0, code.length - 3) + ";}");
163 };
164
165 // private
166 Date.getFormatCode = function(character) {
167     switch (character) {
168     case "d":
169         return "String.leftPad(this.getDate(), 2, '0') + ";
170     case "D":
171         return "Date.dayNames[this.getDay()].substring(0, 3) + ";
172     case "j":
173         return "this.getDate() + ";
174     case "l":
175         return "Date.dayNames[this.getDay()] + ";
176     case "S":
177         return "this.getSuffix() + ";
178     case "w":
179         return "this.getDay() + ";
180     case "z":
181         return "this.getDayOfYear() + ";
182     case "W":
183         return "this.getWeekOfYear() + ";
184     case "F":
185         return "Date.monthNames[this.getMonth()] + ";
186     case "m":
187         return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
188     case "M":
189         return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
190     case "n":
191         return "(this.getMonth() + 1) + ";
192     case "t":
193         return "this.getDaysInMonth() + ";
194     case "L":
195         return "(this.isLeapYear() ? 1 : 0) + ";
196     case "Y":
197         return "this.getFullYear() + ";
198     case "y":
199         return "('' + this.getFullYear()).substring(2, 4) + ";
200     case "a":
201         return "(this.getHours() < 12 ? 'am' : 'pm') + ";
202     case "A":
203         return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
204     case "g":
205         return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
206     case "G":
207         return "this.getHours() + ";
208     case "h":
209         return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
210     case "H":
211         return "String.leftPad(this.getHours(), 2, '0') + ";
212     case "i":
213         return "String.leftPad(this.getMinutes(), 2, '0') + ";
214     case "s":
215         return "String.leftPad(this.getSeconds(), 2, '0') + ";
216     case "O":
217         return "this.getGMTOffset() + ";
218     case "P":
219         return "this.getGMTColonOffset() + ";
220     case "T":
221         return "this.getTimezone() + ";
222     case "Z":
223         return "(this.getTimezoneOffset() * -60) + ";
224     default:
225         return "'" + String.escape(character) + "' + ";
226     }
227 };
228
229 /**
230  * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
231  * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates.  Any part of
232  * the date format that is not specified will default to the current date value for that part.  Time parts can also
233  * be specified, but default to 0.  Keep in mind that the input date string must precisely match the specified format
234  * string or the parse operation will fail.
235  * Example Usage:
236 <pre><code>
237 //dt = Fri May 25 2007 (current date)
238 var dt = new Date();
239
240 //dt = Thu May 25 2006 (today's month/day in 2006)
241 dt = Date.parseDate("2006", "Y");
242
243 //dt = Sun Jan 15 2006 (all date parts specified)
244 dt = Date.parseDate("2006-1-15", "Y-m-d");
245
246 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
247 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
248 </code></pre>
249  * @param {String} input The unparsed date as a string
250  * @param {String} format The format the date is in
251  * @return {Date} The parsed date
252  * @static
253  */
254 Date.parseDate = function(input, format) {
255     if (Date.parseFunctions[format] == null) {
256         Date.createParser(format);
257     }
258     var func = Date.parseFunctions[format];
259     return Date[func](input);
260 };
261 /**
262  * @private
263  */
264 Date.createParser = function(format) {
265     var funcName = "parse" + Date.parseFunctions.count++;
266     var regexNum = Date.parseRegexes.length;
267     var currentGroup = 1;
268     Date.parseFunctions[format] = funcName;
269
270     var code = "Date." + funcName + " = function(input){\n"
271         + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
272         + "var d = new Date();\n"
273         + "y = d.getFullYear();\n"
274         + "m = d.getMonth();\n"
275         + "d = d.getDate();\n"
276         + "if (typeof(input) !== 'string') { input = input.toString(); }\n"
277         + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
278         + "if (results && results.length > 0) {";
279     var regex = "";
280
281     var special = false;
282     var ch = '';
283     for (var i = 0; i < format.length; ++i) {
284         ch = format.charAt(i);
285         if (!special && ch == "\\") {
286             special = true;
287         }
288         else if (special) {
289             special = false;
290             regex += String.escape(ch);
291         }
292         else {
293             var obj = Date.formatCodeToRegex(ch, currentGroup);
294             currentGroup += obj.g;
295             regex += obj.s;
296             if (obj.g && obj.c) {
297                 code += obj.c;
298             }
299         }
300     }
301
302     code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
303         + "{v = new Date(y, m, d, h, i, s);}\n"
304         + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
305         + "{v = new Date(y, m, d, h, i);}\n"
306         + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
307         + "{v = new Date(y, m, d, h);}\n"
308         + "else if (y >= 0 && m >= 0 && d > 0)\n"
309         + "{v = new Date(y, m, d);}\n"
310         + "else if (y >= 0 && m >= 0)\n"
311         + "{v = new Date(y, m);}\n"
312         + "else if (y >= 0)\n"
313         + "{v = new Date(y);}\n"
314         + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
315         + "    ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
316         + "        v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
317         + ";}";
318
319     Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
320     /** eval:var:zzzzzzzzzzzzz */
321     eval(code);
322 };
323
324 // private
325 Date.formatCodeToRegex = function(character, currentGroup) {
326     switch (character) {
327     case "D":
328         return {g:0,
329         c:null,
330         s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
331     case "j":
332         return {g:1,
333             c:"d = parseInt(results[" + currentGroup + "], 10);\n",
334             s:"(\\d{1,2})"}; // day of month without leading zeroes
335     case "d":
336         return {g:1,
337             c:"d = parseInt(results[" + currentGroup + "], 10);\n",
338             s:"(\\d{2})"}; // day of month with leading zeroes
339     case "l":
340         return {g:0,
341             c:null,
342             s:"(?:" + Date.dayNames.join("|") + ")"};
343     case "S":
344         return {g:0,
345             c:null,
346             s:"(?:st|nd|rd|th)"};
347     case "w":
348         return {g:0,
349             c:null,
350             s:"\\d"};
351     case "z":
352         return {g:0,
353             c:null,
354             s:"(?:\\d{1,3})"};
355     case "W":
356         return {g:0,
357             c:null,
358             s:"(?:\\d{2})"};
359     case "F":
360         return {g:1,
361             c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10); d = 1;\n",
362             s:"(" + Date.monthNames.join("|") + ")"};
363     case "M":
364         return {g:1,
365             c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
366             s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
367     case "n":
368         return {g:1,
369             c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
370             s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
371     case "m":
372         return {g:1,
373             c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
374             s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
375     case "t":
376         return {g:0,
377             c:null,
378             s:"\\d{1,2}"};
379     case "L":
380         return {g:0,
381             c:null,
382             s:"(?:1|0)"};
383     case "Y":
384         return {g:1,
385             c:"y = parseInt(results[" + currentGroup + "], 10);\n",
386             s:"(\\d{4})"};
387     case "y":
388         return {g:1,
389             c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
390                 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
391             s:"(\\d{1,2})"};
392     case "a":
393         return {g:1,
394             c:"if (results[" + currentGroup + "] == 'am') {\n"
395                 + "if (h == 12) { h = 0; }\n"
396                 + "} else { if (h < 12) { h += 12; }}",
397             s:"(am|pm)"};
398     case "A":
399         return {g:1,
400             c:"if (results[" + currentGroup + "] == 'AM') {\n"
401                 + "if (h == 12) { h = 0; }\n"
402                 + "} else { if (h < 12) { h += 12; }}",
403             s:"(AM|PM)"};
404     case "g":
405     case "G":
406         return {g:1,
407             c:"h = parseInt(results[" + currentGroup + "], 10);\n",
408             s:"(\\d{1,2})"}; // 12/24-hr format  format of an hour without leading zeroes
409     case "h":
410     case "H":
411         return {g:1,
412             c:"h = parseInt(results[" + currentGroup + "], 10);\n",
413             s:"(\\d{2})"}; //  12/24-hr format  format of an hour with leading zeroes
414     case "i":
415         return {g:1,
416             c:"i = parseInt(results[" + currentGroup + "], 10);\n",
417             s:"(\\d{2})"};
418     case "s":
419         return {g:1,
420             c:"s = parseInt(results[" + currentGroup + "], 10);\n",
421             s:"(\\d{2})"};
422     case "O":
423         return {g:1,
424             c:[
425                 "o = results[", currentGroup, "];\n",
426                 "var sn = o.substring(0,1);\n", // get + / - sign
427                 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
428                 "var mn = o.substring(3,5) % 60;\n", // get minutes
429                 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
430                 "    (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
431             ].join(""),
432             s:"([+\-]\\d{2,4})"};
433     
434     
435     case "P":
436         return {g:1,
437                 c:[
438                    "o = results[", currentGroup, "];\n",
439                    "var sn = o.substring(0,1);\n",
440                    "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
441                    "var mn = o.substring(4,6) % 60;\n",
442                    "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
443                         "    (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
444             ].join(""),
445             s:"([+\-]\\d{4})"};
446     case "T":
447         return {g:0,
448             c:null,
449             s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
450     case "Z":
451         return {g:1,
452             c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
453                   + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
454             s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
455     default:
456         return {g:0,
457             c:null,
458             s:String.escape(character)};
459     }
460 };
461
462 /**
463  * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
464  * @return {String} The abbreviated timezone name (e.g. 'CST')
465  */
466 Date.prototype.getTimezone = function() {
467     return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
468 };
469
470 /**
471  * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
472  * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
473  */
474 Date.prototype.getGMTOffset = function() {
475     return (this.getTimezoneOffset() > 0 ? "-" : "+")
476         + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
477         + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
478 };
479
480 /**
481  * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
482  * @return {String} 2-characters representing hours and 2-characters representing minutes
483  * seperated by a colon and prefixed with + or - (e.g. '-06:00')
484  */
485 Date.prototype.getGMTColonOffset = function() {
486         return (this.getTimezoneOffset() > 0 ? "-" : "+")
487                 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
488                 + ":"
489                 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
490 }
491
492 /**
493  * Get the numeric day number of the year, adjusted for leap year.
494  * @return {Number} 0 through 364 (365 in leap years)
495  */
496 Date.prototype.getDayOfYear = function() {
497     var num = 0;
498     Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
499     for (var i = 0; i < this.getMonth(); ++i) {
500         num += Date.daysInMonth[i];
501     }
502     return num + this.getDate() - 1;
503 };
504
505 /**
506  * Get the string representation of the numeric week number of the year
507  * (equivalent to the format specifier 'W').
508  * @return {String} '00' through '52'
509  */
510 Date.prototype.getWeekOfYear = function() {
511     // Skip to Thursday of this week
512     var now = this.getDayOfYear() + (4 - this.getDay());
513     // Find the first Thursday of the year
514     var jan1 = new Date(this.getFullYear(), 0, 1);
515     var then = (7 - jan1.getDay() + 4);
516     return String.leftPad(((now - then) / 7) + 1, 2, "0");
517 };
518
519 /**
520  * Whether or not the current date is in a leap year.
521  * @return {Boolean} True if the current date is in a leap year, else false
522  */
523 Date.prototype.isLeapYear = function() {
524     var year = this.getFullYear();
525     return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
526 };
527
528 /**
529  * Get the first day of the current month, adjusted for leap year.  The returned value
530  * is the numeric day index within the week (0-6) which can be used in conjunction with
531  * the {@link #monthNames} array to retrieve the textual day name.
532  * Example:
533  *<pre><code>
534 var dt = new Date('1/10/2007');
535 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
536 </code></pre>
537  * @return {Number} The day number (0-6)
538  */
539 Date.prototype.getFirstDayOfMonth = function() {
540     var day = (this.getDay() - (this.getDate() - 1)) % 7;
541     return (day < 0) ? (day + 7) : day;
542 };
543
544 /**
545  * Get the last day of the current month, adjusted for leap year.  The returned value
546  * is the numeric day index within the week (0-6) which can be used in conjunction with
547  * the {@link #monthNames} array to retrieve the textual day name.
548  * Example:
549  *<pre><code>
550 var dt = new Date('1/10/2007');
551 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
552 </code></pre>
553  * @return {Number} The day number (0-6)
554  */
555 Date.prototype.getLastDayOfMonth = function() {
556     var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
557     return (day < 0) ? (day + 7) : day;
558 };
559
560
561 /**
562  * Get the first date of this date's month
563  * @return {Date}
564  */
565 Date.prototype.getFirstDateOfMonth = function() {
566     return new Date(this.getFullYear(), this.getMonth(), 1);
567 };
568
569 /**
570  * Get the last date of this date's month
571  * @return {Date}
572  */
573 Date.prototype.getLastDateOfMonth = function() {
574     return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
575 };
576 /**
577  * Get the number of days in the current month, adjusted for leap year.
578  * @return {Number} The number of days in the month
579  */
580 Date.prototype.getDaysInMonth = function() {
581     Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
582     return Date.daysInMonth[this.getMonth()];
583 };
584
585 /**
586  * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
587  * @return {String} 'st, 'nd', 'rd' or 'th'
588  */
589 Date.prototype.getSuffix = function() {
590     switch (this.getDate()) {
591         case 1:
592         case 21:
593         case 31:
594             return "st";
595         case 2:
596         case 22:
597             return "nd";
598         case 3:
599         case 23:
600             return "rd";
601         default:
602             return "th";
603     }
604 };
605
606 // private
607 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
608
609 /**
610  * An array of textual month names.
611  * Override these values for international dates, for example...
612  * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
613  * @type Array
614  * @static
615  */
616 Date.monthNames =
617    ["January",
618     "February",
619     "March",
620     "April",
621     "May",
622     "June",
623     "July",
624     "August",
625     "September",
626     "October",
627     "November",
628     "December"];
629
630 /**
631  * An array of textual day names.
632  * Override these values for international dates, for example...
633  * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
634  * @type Array
635  * @static
636  */
637 Date.dayNames =
638    ["Sunday",
639     "Monday",
640     "Tuesday",
641     "Wednesday",
642     "Thursday",
643     "Friday",
644     "Saturday"];
645
646 // private
647 Date.y2kYear = 50;
648 // private
649 Date.monthNumbers = {
650     Jan:0,
651     Feb:1,
652     Mar:2,
653     Apr:3,
654     May:4,
655     Jun:5,
656     Jul:6,
657     Aug:7,
658     Sep:8,
659     Oct:9,
660     Nov:10,
661     Dec:11};
662
663 /**
664  * Creates and returns a new Date instance with the exact same date value as the called instance.
665  * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
666  * variable will also be changed.  When the intention is to create a new variable that will not
667  * modify the original instance, you should create a clone.
668  *
669  * Example of correctly cloning a date:
670  * <pre><code>
671 //wrong way:
672 var orig = new Date('10/1/2006');
673 var copy = orig;
674 copy.setDate(5);
675 document.write(orig);  //returns 'Thu Oct 05 2006'!
676
677 //correct way:
678 var orig = new Date('10/1/2006');
679 var copy = orig.clone();
680 copy.setDate(5);
681 document.write(orig);  //returns 'Thu Oct 01 2006'
682 </code></pre>
683  * @return {Date} The new Date instance
684  */
685 Date.prototype.clone = function() {
686         return new Date(this.getTime());
687 };
688
689 /**
690  * Clears any time information from this date
691  @param {Boolean} clone true to create a clone of this date, clear the time and return it
692  @return {Date} this or the clone
693  */
694 Date.prototype.clearTime = function(clone){
695     if(clone){
696         return this.clone().clearTime();
697     }
698     this.setHours(0);
699     this.setMinutes(0);
700     this.setSeconds(0);
701     this.setMilliseconds(0);
702     return this;
703 };
704
705 // private
706 // safari setMonth is broken
707 if(Roo.isSafari){
708     Date.brokenSetMonth = Date.prototype.setMonth;
709         Date.prototype.setMonth = function(num){
710                 if(num <= -1){
711                         var n = Math.ceil(-num);
712                         var back_year = Math.ceil(n/12);
713                         var month = (n % 12) ? 12 - n % 12 : 0 ;
714                         this.setFullYear(this.getFullYear() - back_year);
715                         return Date.brokenSetMonth.call(this, month);
716                 } else {
717                         return Date.brokenSetMonth.apply(this, arguments);
718                 }
719         };
720 }
721
722 /** Date interval constant 
723 * @static 
724 * @type String */
725 Date.MILLI = "ms";
726 /** Date interval constant 
727 * @static 
728 * @type String */
729 Date.SECOND = "s";
730 /** Date interval constant 
731 * @static 
732 * @type String */
733 Date.MINUTE = "mi";
734 /** Date interval constant 
735 * @static 
736 * @type String */
737 Date.HOUR = "h";
738 /** Date interval constant 
739 * @static 
740 * @type String */
741 Date.DAY = "d";
742 /** Date interval constant 
743 * @static 
744 * @type String */
745 Date.MONTH = "mo";
746 /** Date interval constant 
747 * @static 
748 * @type String */
749 Date.YEAR = "y";
750
751 /**
752  * Provides a convenient method of performing basic date arithmetic.  This method
753  * does not modify the Date instance being called - it creates and returns
754  * a new Date instance containing the resulting date value.
755  *
756  * Examples:
757  * <pre><code>
758 //Basic usage:
759 var dt = new Date('10/29/2006').add(Date.DAY, 5);
760 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
761
762 //Negative values will subtract correctly:
763 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
764 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
765
766 //You can even chain several calls together in one line!
767 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
768 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
769  </code></pre>
770  *
771  * @param {String} interval   A valid date interval enum value
772  * @param {Number} value      The amount to add to the current date
773  * @return {Date} The new Date instance
774  */
775 Date.prototype.add = function(interval, value){
776   var d = this.clone();
777   if (!interval || value === 0) return d;
778   switch(interval.toLowerCase()){
779     case Date.MILLI:
780       d.setMilliseconds(this.getMilliseconds() + value);
781       break;
782     case Date.SECOND:
783       d.setSeconds(this.getSeconds() + value);
784       break;
785     case Date.MINUTE:
786       d.setMinutes(this.getMinutes() + value);
787       break;
788     case Date.HOUR:
789       d.setHours(this.getHours() + value);
790       break;
791     case Date.DAY:
792       d.setDate(this.getDate() + value);
793       break;
794     case Date.MONTH:
795       var day = this.getDate();
796       if(day > 28){
797           day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
798       }
799       d.setDate(day);
800       d.setMonth(this.getMonth() + value);
801       break;
802     case Date.YEAR:
803       d.setFullYear(this.getFullYear() + value);
804       break;
805   }
806   return d;
807 };