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