initial import
[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 Date.createParser = function(format) {
261     var funcName = "parse" + Date.parseFunctions.count++;
262     var regexNum = Date.parseRegexes.length;
263     var currentGroup = 1;
264     Date.parseFunctions[format] = funcName;
265
266     var code = "Date." + funcName + " = function(input){\n"
267         + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
268         + "var d = new Date();\n"
269         + "y = d.getFullYear();\n"
270         + "m = d.getMonth();\n"
271         + "d = d.getDate();\n"
272         + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
273         + "if (results && results.length > 0) {";
274     var regex = "";
275
276     var special = false;
277     var ch = '';
278     for (var i = 0; i < format.length; ++i) {
279         ch = format.charAt(i);
280         if (!special && ch == "\\") {
281             special = true;
282         }
283         else if (special) {
284             special = false;
285             regex += String.escape(ch);
286         }
287         else {
288             var obj = Date.formatCodeToRegex(ch, currentGroup);
289             currentGroup += obj.g;
290             regex += obj.s;
291             if (obj.g && obj.c) {
292                 code += obj.c;
293             }
294         }
295     }
296
297     code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
298         + "{v = new Date(y, m, d, h, i, s);}\n"
299         + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
300         + "{v = new Date(y, m, d, h, i);}\n"
301         + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
302         + "{v = new Date(y, m, d, h);}\n"
303         + "else if (y >= 0 && m >= 0 && d > 0)\n"
304         + "{v = new Date(y, m, d);}\n"
305         + "else if (y >= 0 && m >= 0)\n"
306         + "{v = new Date(y, m);}\n"
307         + "else if (y >= 0)\n"
308         + "{v = new Date(y);}\n"
309         + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
310         + "    ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
311         + "        v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
312         + ";}";
313
314     Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
315      /** eval:var:zzzzzzzzzzzzz */
316     eval(code);
317 };
318
319 // private
320 Date.formatCodeToRegex = function(character, currentGroup) {
321     switch (character) {
322     case "D":
323         return {g:0,
324         c:null,
325         s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
326     case "j":
327         return {g:1,
328             c:"d = parseInt(results[" + currentGroup + "], 10);\n",
329             s:"(\\d{1,2})"}; // day of month without leading zeroes
330     case "d":
331         return {g:1,
332             c:"d = parseInt(results[" + currentGroup + "], 10);\n",
333             s:"(\\d{2})"}; // day of month with leading zeroes
334     case "l":
335         return {g:0,
336             c:null,
337             s:"(?:" + Date.dayNames.join("|") + ")"};
338     case "S":
339         return {g:0,
340             c:null,
341             s:"(?:st|nd|rd|th)"};
342     case "w":
343         return {g:0,
344             c:null,
345             s:"\\d"};
346     case "z":
347         return {g:0,
348             c:null,
349             s:"(?:\\d{1,3})"};
350     case "W":
351         return {g:0,
352             c:null,
353             s:"(?:\\d{2})"};
354     case "F":
355         return {g:1,
356             c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
357             s:"(" + Date.monthNames.join("|") + ")"};
358     case "M":
359         return {g:1,
360             c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
361             s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
362     case "n":
363         return {g:1,
364             c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
365             s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
366     case "m":
367         return {g:1,
368             c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
369             s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
370     case "t":
371         return {g:0,
372             c:null,
373             s:"\\d{1,2}"};
374     case "L":
375         return {g:0,
376             c:null,
377             s:"(?:1|0)"};
378     case "Y":
379         return {g:1,
380             c:"y = parseInt(results[" + currentGroup + "], 10);\n",
381             s:"(\\d{4})"};
382     case "y":
383         return {g:1,
384             c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
385                 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
386             s:"(\\d{1,2})"};
387     case "a":
388         return {g:1,
389             c:"if (results[" + currentGroup + "] == 'am') {\n"
390                 + "if (h == 12) { h = 0; }\n"
391                 + "} else { if (h < 12) { h += 12; }}",
392             s:"(am|pm)"};
393     case "A":
394         return {g:1,
395             c:"if (results[" + currentGroup + "] == 'AM') {\n"
396                 + "if (h == 12) { h = 0; }\n"
397                 + "} else { if (h < 12) { h += 12; }}",
398             s:"(AM|PM)"};
399     case "g":
400     case "G":
401         return {g:1,
402             c:"h = parseInt(results[" + currentGroup + "], 10);\n",
403             s:"(\\d{1,2})"}; // 12/24-hr format  format of an hour without leading zeroes
404     case "h":
405     case "H":
406         return {g:1,
407             c:"h = parseInt(results[" + currentGroup + "], 10);\n",
408             s:"(\\d{2})"}; //  12/24-hr format  format of an hour with leading zeroes
409     case "i":
410         return {g:1,
411             c:"i = parseInt(results[" + currentGroup + "], 10);\n",
412             s:"(\\d{2})"};
413     case "s":
414         return {g:1,
415             c:"s = parseInt(results[" + currentGroup + "], 10);\n",
416             s:"(\\d{2})"};
417     case "O":
418         return {g:1,
419             c:[
420                 "o = results[", currentGroup, "];\n",
421                 "var sn = o.substring(0,1);\n", // get + / - sign
422                 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
423                 "var mn = o.substring(3,5) % 60;\n", // get minutes
424                 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
425                 "    (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
426             ].join(""),
427             s:"([+\-]\\d{4})"};
428     case "T":
429         return {g:0,
430             c:null,
431             s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
432     case "Z":
433         return {g:1,
434             c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
435                   + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
436             s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
437     default:
438         return {g:0,
439             c:null,
440             s:String.escape(character)};
441     }
442 };
443
444 /**
445  * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
446  * @return {String} The abbreviated timezone name (e.g. 'CST')
447  */
448 Date.prototype.getTimezone = function() {
449     return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
450 };
451
452 /**
453  * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
454  * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
455  */
456 Date.prototype.getGMTOffset = function() {
457     return (this.getTimezoneOffset() > 0 ? "-" : "+")
458         + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
459         + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
460 };
461
462 /**
463  * Get the numeric day number of the year, adjusted for leap year.
464  * @return {Number} 0 through 364 (365 in leap years)
465  */
466 Date.prototype.getDayOfYear = function() {
467     var num = 0;
468     Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
469     for (var i = 0; i < this.getMonth(); ++i) {
470         num += Date.daysInMonth[i];
471     }
472     return num + this.getDate() - 1;
473 };
474
475 /**
476  * Get the string representation of the numeric week number of the year
477  * (equivalent to the format specifier 'W').
478  * @return {String} '00' through '52'
479  */
480 Date.prototype.getWeekOfYear = function() {
481     // Skip to Thursday of this week
482     var now = this.getDayOfYear() + (4 - this.getDay());
483     // Find the first Thursday of the year
484     var jan1 = new Date(this.getFullYear(), 0, 1);
485     var then = (7 - jan1.getDay() + 4);
486     return String.leftPad(((now - then) / 7) + 1, 2, "0");
487 };
488
489 /**
490  * Whether or not the current date is in a leap year.
491  * @return {Boolean} True if the current date is in a leap year, else false
492  */
493 Date.prototype.isLeapYear = function() {
494     var year = this.getFullYear();
495     return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
496 };
497
498 /**
499  * Get the first day of the current month, adjusted for leap year.  The returned value
500  * is the numeric day index within the week (0-6) which can be used in conjunction with
501  * the {@link #monthNames} array to retrieve the textual day name.
502  * Example:
503  *<pre><code>
504 var dt = new Date('1/10/2007');
505 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
506 </code></pre>
507  * @return {Number} The day number (0-6)
508  */
509 Date.prototype.getFirstDayOfMonth = function() {
510     var day = (this.getDay() - (this.getDate() - 1)) % 7;
511     return (day < 0) ? (day + 7) : day;
512 };
513
514 /**
515  * Get the last day of the current month, adjusted for leap year.  The returned value
516  * is the numeric day index within the week (0-6) which can be used in conjunction with
517  * the {@link #monthNames} array to retrieve the textual day name.
518  * Example:
519  *<pre><code>
520 var dt = new Date('1/10/2007');
521 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
522 </code></pre>
523  * @return {Number} The day number (0-6)
524  */
525 Date.prototype.getLastDayOfMonth = function() {
526     var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
527     return (day < 0) ? (day + 7) : day;
528 };
529
530
531 /**
532  * Get the first date of this date's month
533  * @return {Date}
534  */
535 Date.prototype.getFirstDateOfMonth = function() {
536     return new Date(this.getFullYear(), this.getMonth(), 1);
537 };
538
539 /**
540  * Get the last date of this date's month
541  * @return {Date}
542  */
543 Date.prototype.getLastDateOfMonth = function() {
544     return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
545 };
546 /**
547  * Get the number of days in the current month, adjusted for leap year.
548  * @return {Number} The number of days in the month
549  */
550 Date.prototype.getDaysInMonth = function() {
551     Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
552     return Date.daysInMonth[this.getMonth()];
553 };
554
555 /**
556  * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
557  * @return {String} 'st, 'nd', 'rd' or 'th'
558  */
559 Date.prototype.getSuffix = function() {
560     switch (this.getDate()) {
561         case 1:
562         case 21:
563         case 31:
564             return "st";
565         case 2:
566         case 22:
567             return "nd";
568         case 3:
569         case 23:
570             return "rd";
571         default:
572             return "th";
573     }
574 };
575
576 // private
577 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
578
579 /**
580  * An array of textual month names.
581  * Override these values for international dates, for example...
582  * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
583  * @type Array
584  * @static
585  */
586 Date.monthNames =
587    ["January",
588     "February",
589     "March",
590     "April",
591     "May",
592     "June",
593     "July",
594     "August",
595     "September",
596     "October",
597     "November",
598     "December"];
599
600 /**
601  * An array of textual day names.
602  * Override these values for international dates, for example...
603  * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
604  * @type Array
605  * @static
606  */
607 Date.dayNames =
608    ["Sunday",
609     "Monday",
610     "Tuesday",
611     "Wednesday",
612     "Thursday",
613     "Friday",
614     "Saturday"];
615
616 // private
617 Date.y2kYear = 50;
618 // private
619 Date.monthNumbers = {
620     Jan:0,
621     Feb:1,
622     Mar:2,
623     Apr:3,
624     May:4,
625     Jun:5,
626     Jul:6,
627     Aug:7,
628     Sep:8,
629     Oct:9,
630     Nov:10,
631     Dec:11};
632
633 /**
634  * Creates and returns a new Date instance with the exact same date value as the called instance.
635  * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
636  * variable will also be changed.  When the intention is to create a new variable that will not
637  * modify the original instance, you should create a clone.
638  *
639  * Example of correctly cloning a date:
640  * <pre><code>
641 //wrong way:
642 var orig = new Date('10/1/2006');
643 var copy = orig;
644 copy.setDate(5);
645 document.write(orig);  //returns 'Thu Oct 05 2006'!
646
647 //correct way:
648 var orig = new Date('10/1/2006');
649 var copy = orig.clone();
650 copy.setDate(5);
651 document.write(orig);  //returns 'Thu Oct 01 2006'
652 </code></pre>
653  * @return {Date} The new Date instance
654  */
655 Date.prototype.clone = function() {
656         return new Date(this.getTime());
657 };
658
659 /**
660  * Clears any time information from this date
661  @param {Boolean} clone true to create a clone of this date, clear the time and return it
662  @return {Date} this or the clone
663  */
664 Date.prototype.clearTime = function(clone){
665     if(clone){
666         return this.clone().clearTime();
667     }
668     this.setHours(0);
669     this.setMinutes(0);
670     this.setSeconds(0);
671     this.setMilliseconds(0);
672     return this;
673 };
674
675 // private
676 // safari setMonth is broken
677 if(Roo.isSafari){
678     Date.brokenSetMonth = Date.prototype.setMonth;
679         Date.prototype.setMonth = function(num){
680                 if(num <= -1){
681                         var n = Math.ceil(-num);
682                         var back_year = Math.ceil(n/12);
683                         var month = (n % 12) ? 12 - n % 12 : 0 ;
684                         this.setFullYear(this.getFullYear() - back_year);
685                         return Date.brokenSetMonth.call(this, month);
686                 } else {
687                         return Date.brokenSetMonth.apply(this, arguments);
688                 }
689         };
690 }
691
692 /** Date interval constant 
693 * @static 
694 * @type String */
695 Date.MILLI = "ms";
696 /** Date interval constant 
697 * @static 
698 * @type String */
699 Date.SECOND = "s";
700 /** Date interval constant 
701 * @static 
702 * @type String */
703 Date.MINUTE = "mi";
704 /** Date interval constant 
705 * @static 
706 * @type String */
707 Date.HOUR = "h";
708 /** Date interval constant 
709 * @static 
710 * @type String */
711 Date.DAY = "d";
712 /** Date interval constant 
713 * @static 
714 * @type String */
715 Date.MONTH = "mo";
716 /** Date interval constant 
717 * @static 
718 * @type String */
719 Date.YEAR = "y";
720
721 /**
722  * Provides a convenient method of performing basic date arithmetic.  This method
723  * does not modify the Date instance being called - it creates and returns
724  * a new Date instance containing the resulting date value.
725  *
726  * Examples:
727  * <pre><code>
728 //Basic usage:
729 var dt = new Date('10/29/2006').add(Date.DAY, 5);
730 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
731
732 //Negative values will subtract correctly:
733 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
734 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
735
736 //You can even chain several calls together in one line!
737 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
738 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
739  </code></pre>
740  *
741  * @param {String} interval   A valid date interval enum value
742  * @param {Number} value      The amount to add to the current date
743  * @return {Date} The new Date instance
744  */
745 Date.prototype.add = function(interval, value){
746   var d = this.clone();
747   if (!interval || value === 0) return d;
748   switch(interval.toLowerCase()){
749     case Date.MILLI:
750       d.setMilliseconds(this.getMilliseconds() + value);
751       break;
752     case Date.SECOND:
753       d.setSeconds(this.getSeconds() + value);
754       break;
755     case Date.MINUTE:
756       d.setMinutes(this.getMinutes() + value);
757       break;
758     case Date.HOUR:
759       d.setHours(this.getHours() + value);
760       break;
761     case Date.DAY:
762       d.setDate(this.getDate() + value);
763       break;
764     case Date.MONTH:
765       var day = this.getDate();
766       if(day > 28){
767           day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
768       }
769       d.setDate(day);
770       d.setMonth(this.getMonth() + value);
771       break;
772     case Date.YEAR:
773       d.setFullYear(this.getFullYear() + value);
774       break;
775   }
776   return d;
777 };