Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / core / src / lang / Date.js
1 /**
2  * @class Ext.Date
3  * A set of useful static methods to deal with date
4  * Note that if Ext.Date is required and loaded, it will copy all methods / properties to
5  * this object for convenience
6  *
7  * The date parsing and formatting syntax contains a subset of
8  * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
9  * supported will provide results equivalent to their PHP versions.
10  *
11  * The following is a list of all currently supported formats:
12  * <pre class="">
13 Format  Description                                                               Example returned values
14 ------  -----------------------------------------------------------------------   -----------------------
15   d     Day of the month, 2 digits with leading zeros                             01 to 31
16   D     A short textual representation of the day of the week                     Mon to Sun
17   j     Day of the month without leading zeros                                    1 to 31
18   l     A full textual representation of the day of the week                      Sunday to Saturday
19   N     ISO-8601 numeric representation of the day of the week                    1 (for Monday) through 7 (for Sunday)
20   S     English ordinal suffix for the day of the month, 2 characters             st, nd, rd or th. Works well with j
21   w     Numeric representation of the day of the week                             0 (for Sunday) to 6 (for Saturday)
22   z     The day of the year (starting from 0)                                     0 to 364 (365 in leap years)
23   W     ISO-8601 week number of year, weeks starting on Monday                    01 to 53
24   F     A full textual representation of a month, such as January or March        January to December
25   m     Numeric representation of a month, with leading zeros                     01 to 12
26   M     A short textual representation of a month                                 Jan to Dec
27   n     Numeric representation of a month, without leading zeros                  1 to 12
28   t     Number of days in the given month                                         28 to 31
29   L     Whether it&#39;s a leap year                                                  1 if it is a leap year, 0 otherwise.
30   o     ISO-8601 year number (identical to (Y), but if the ISO week number (W)    Examples: 1998 or 2004
31         belongs to the previous or next year, that year is used instead)
32   Y     A full numeric representation of a year, 4 digits                         Examples: 1999 or 2003
33   y     A two digit representation of a year                                      Examples: 99 or 03
34   a     Lowercase Ante meridiem and Post meridiem                                 am or pm
35   A     Uppercase Ante meridiem and Post meridiem                                 AM or PM
36   g     12-hour format of an hour without leading zeros                           1 to 12
37   G     24-hour format of an hour without leading zeros                           0 to 23
38   h     12-hour format of an hour with leading zeros                              01 to 12
39   H     24-hour format of an hour with leading zeros                              00 to 23
40   i     Minutes, with leading zeros                                               00 to 59
41   s     Seconds, with leading zeros                                               00 to 59
42   u     Decimal fraction of a second                                              Examples:
43         (minimum 1 digit, arbitrary number of digits allowed)                     001 (i.e. 0.001s) or
44                                                                                   100 (i.e. 0.100s) or
45                                                                                   999 (i.e. 0.999s) or
46                                                                                   999876543210 (i.e. 0.999876543210s)
47   O     Difference to Greenwich time (GMT) in hours and minutes                   Example: +1030
48   P     Difference to Greenwich time (GMT) with colon between hours and minutes   Example: -08:00
49   T     Timezone abbreviation of the machine running the code                     Examples: EST, MDT, PDT ...
50   Z     Timezone offset in seconds (negative if west of UTC, positive if east)    -43200 to 50400
51   c     ISO 8601 date
52         Notes:                                                                    Examples:
53         1) If unspecified, the month / day defaults to the current month / day,   1991 or
54            the time defaults to midnight, while the timezone defaults to the      1992-10 or
55            browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
56            and minutes. The "T" delimiter, seconds, milliseconds and timezone     1994-08-19T16:20+01:00 or
57            are optional.                                                          1995-07-18T17:21:28-02:00 or
58         2) The decimal fraction of a second, if specified, must contain at        1996-06-17T18:22:29.98765+03:00 or
59            least 1 digit (there is no limit to the maximum number                 1997-05-16T19:23:30,12345-0400 or
60            of digits allowed), and may be delimited by either a '.' or a ','      1998-04-15T20:24:31.2468Z or
61         Refer to the examples on the right for the various levels of              1999-03-14T20:24:32Z or
62         date-time granularity which are supported, or see                         2000-02-13T21:25:33
63         http://www.w3.org/TR/NOTE-datetime for more info.                         2001-01-12 22:26:34
64   U     Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)                1193432466 or -2138434463
65   MS    Microsoft AJAX serialized dates                                           \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
66                                                                                   \/Date(1238606590509+0800)\/
67 </pre>
68  *
69  * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
70  * <pre><code>
71 // Sample date:
72 // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
73
74 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
75 console.log(Ext.Date.format(dt, 'Y-m-d'));                          // 2007-01-10
76 console.log(Ext.Date.format(dt, 'F j, Y, g:i a'));                  // January 10, 2007, 3:05 pm
77 console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
78 </code></pre>
79  *
80  * Here are some standard date/time patterns that you might find helpful.  They
81  * are not part of the source of Ext.Date, but to use them you can simply copy this
82  * block of code into any script that is included after Ext.Date and they will also become
83  * globally available on the Date object.  Feel free to add or remove patterns as needed in your code.
84  * <pre><code>
85 Ext.Date.patterns = {
86     ISO8601Long:"Y-m-d H:i:s",
87     ISO8601Short:"Y-m-d",
88     ShortDate: "n/j/Y",
89     LongDate: "l, F d, Y",
90     FullDateTime: "l, F d, Y g:i:s A",
91     MonthDay: "F d",
92     ShortTime: "g:i A",
93     LongTime: "g:i:s A",
94     SortableDateTime: "Y-m-d\\TH:i:s",
95     UniversalSortableDateTime: "Y-m-d H:i:sO",
96     YearMonth: "F, Y"
97 };
98 </code></pre>
99  *
100  * Example usage:
101  * <pre><code>
102 var dt = new Date();
103 console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
104 </code></pre>
105  * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
106  * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
107  * @singleton
108  */
109
110 /*
111  * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
112  * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
113  * They generate precompiled functions from format patterns instead of parsing and
114  * processing each pattern every time a date is formatted. These functions are available
115  * on every Date object.
116  */
117
118 (function() {
119
120 // create private copy of Ext's Ext.util.Format.format() method
121 // - to remove unnecessary dependency
122 // - to resolve namespace conflict with MS-Ajax's implementation
123 function xf(format) {
124     var args = Array.prototype.slice.call(arguments, 1);
125     return format.replace(/\{(\d+)\}/g, function(m, i) {
126         return args[i];
127     });
128 }
129
130 Ext.Date = {
131     /**
132      * Returns the current timestamp
133      * @return {Date} The current timestamp
134      */
135     now: Date.now || function() {
136         return +new Date();
137     },
138
139     /**
140      * @private
141      * Private for now
142      */
143     toString: function(date) {
144         var pad = Ext.String.leftPad;
145
146         return date.getFullYear() + "-"
147             + pad(date.getMonth() + 1, 2, '0') + "-"
148             + pad(date.getDate(), 2, '0') + "T"
149             + pad(date.getHours(), 2, '0') + ":"
150             + pad(date.getMinutes(), 2, '0') + ":"
151             + pad(date.getSeconds(), 2, '0');
152     },
153
154     /**
155      * Returns the number of milliseconds between two dates
156      * @param {Date} dateA The first date
157      * @param {Date} dateB (optional) The second date, defaults to now
158      * @return {Number} The difference in milliseconds
159      */
160     getElapsed: function(dateA, dateB) {
161         return Math.abs(dateA - (dateB || new Date()));
162     },
163
164     /**
165      * Global flag which determines if strict date parsing should be used.
166      * Strict date parsing will not roll-over invalid dates, which is the
167      * default behaviour of javascript Date objects.
168      * (see {@link #parse} for more information)
169      * Defaults to <tt>false</tt>.
170      * @static
171      * @type Boolean
172     */
173     useStrict: false,
174
175     // private
176     formatCodeToRegex: function(character, currentGroup) {
177         // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below)
178         var p = utilDate.parseCodes[character];
179
180         if (p) {
181           p = typeof p == 'function'? p() : p;
182           utilDate.parseCodes[character] = p; // reassign function result to prevent repeated execution
183         }
184
185         return p ? Ext.applyIf({
186           c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
187         }, p) : {
188             g: 0,
189             c: null,
190             s: Ext.String.escapeRegex(character) // treat unrecognised characters as literals
191         };
192     },
193
194     /**
195      * <p>An object hash in which each property is a date parsing function. The property name is the
196      * format string which that function parses.</p>
197      * <p>This object is automatically populated with date parsing functions as
198      * date formats are requested for Ext standard formatting strings.</p>
199      * <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
200      * may be used as a format string to {@link #parse}.<p>
201      * <p>Example:</p><pre><code>
202 Ext.Date.parseFunctions['x-date-format'] = myDateParser;
203 </code></pre>
204      * <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
205      * <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
206      * <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
207      * (i.e. prevent javascript Date "rollover") (The default must be false).
208      * Invalid date strings should return null when parsed.</div></li>
209      * </ul></div></p>
210      * <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding
211      * formatting function must be placed into the {@link #formatFunctions} property.
212      * @property parseFunctions
213      * @static
214      * @type Object
215      */
216     parseFunctions: {
217         "MS": function(input, strict) {
218             // note: the timezone offset is ignored since the MS Ajax server sends
219             // a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
220             var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/');
221             var r = (input || '').match(re);
222             return r? new Date(((r[1] || '') + r[2]) * 1) : null;
223         }
224     },
225     parseRegexes: [],
226
227     /**
228      * <p>An object hash in which each property is a date formatting function. The property name is the
229      * format string which corresponds to the produced formatted date string.</p>
230      * <p>This object is automatically populated with date formatting functions as
231      * date formats are requested for Ext standard formatting strings.</p>
232      * <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
233      * may be used as a format string to {@link #format}. Example:</p><pre><code>
234 Ext.Date.formatFunctions['x-date-format'] = myDateFormatter;
235 </code></pre>
236      * <p>A formatting function should return a string representation of the passed Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
237      * <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
238      * </ul></div></p>
239      * <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding
240      * parsing function must be placed into the {@link #parseFunctions} property.
241      * @property formatFunctions
242      * @static
243      * @type Object
244      */
245     formatFunctions: {
246         "MS": function() {
247             // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF))
248             return '\\/Date(' + this.getTime() + ')\\/';
249         }
250     },
251
252     y2kYear : 50,
253
254     /**
255      * Date interval constant
256      * @static
257      * @type String
258      */
259     MILLI : "ms",
260
261     /**
262      * Date interval constant
263      * @static
264      * @type String
265      */
266     SECOND : "s",
267
268     /**
269      * Date interval constant
270      * @static
271      * @type String
272      */
273     MINUTE : "mi",
274
275     /** Date interval constant
276      * @static
277      * @type String
278      */
279     HOUR : "h",
280
281     /**
282      * Date interval constant
283      * @static
284      * @type String
285      */
286     DAY : "d",
287
288     /**
289      * Date interval constant
290      * @static
291      * @type String
292      */
293     MONTH : "mo",
294
295     /**
296      * Date interval constant
297      * @static
298      * @type String
299      */
300     YEAR : "y",
301
302     /**
303      * <p>An object hash containing default date values used during date parsing.</p>
304      * <p>The following properties are available:<div class="mdetail-params"><ul>
305      * <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
306      * <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
307      * <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
308      * <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
309      * <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
310      * <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
311      * <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
312      * </ul></div></p>
313      * <p>Override these properties to customize the default date values used by the {@link #parse} method.</p>
314      * <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
315      * and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
316      * It is the responsiblity of the developer to account for this.</b></p>
317      * Example Usage:
318      * <pre><code>
319 // set default day value to the first day of the month
320 Ext.Date.defaults.d = 1;
321
322 // parse a February date string containing only year and month values.
323 // setting the default day value to 1 prevents weird date rollover issues
324 // when attempting to parse the following date string on, for example, March 31st 2009.
325 Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
326 </code></pre>
327      * @property defaults
328      * @static
329      * @type Object
330      */
331     defaults: {},
332
333     /**
334      * An array of textual day names.
335      * Override these values for international dates.
336      * Example:
337      * <pre><code>
338 Ext.Date.dayNames = [
339     'SundayInYourLang',
340     'MondayInYourLang',
341     ...
342 ];
343 </code></pre>
344      * @type Array
345      * @static
346      */
347     dayNames : [
348         "Sunday",
349         "Monday",
350         "Tuesday",
351         "Wednesday",
352         "Thursday",
353         "Friday",
354         "Saturday"
355     ],
356
357     /**
358      * An array of textual month names.
359      * Override these values for international dates.
360      * Example:
361      * <pre><code>
362 Ext.Date.monthNames = [
363     'JanInYourLang',
364     'FebInYourLang',
365     ...
366 ];
367 </code></pre>
368      * @type Array
369      * @static
370      */
371     monthNames : [
372         "January",
373         "February",
374         "March",
375         "April",
376         "May",
377         "June",
378         "July",
379         "August",
380         "September",
381         "October",
382         "November",
383         "December"
384     ],
385
386     /**
387      * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
388      * Override these values for international dates.
389      * Example:
390      * <pre><code>
391 Ext.Date.monthNumbers = {
392     'ShortJanNameInYourLang':0,
393     'ShortFebNameInYourLang':1,
394     ...
395 };
396 </code></pre>
397      * @type Object
398      * @static
399      */
400     monthNumbers : {
401         Jan:0,
402         Feb:1,
403         Mar:2,
404         Apr:3,
405         May:4,
406         Jun:5,
407         Jul:6,
408         Aug:7,
409         Sep:8,
410         Oct:9,
411         Nov:10,
412         Dec:11
413     },
414     /**
415      * <p>The date format string that the {@link #dateRenderer} and {@link #date} functions use.
416      * see {@link #Date} for details.</p>
417      * <p>This defaults to <code>m/d/Y</code>, but may be overridden in a locale file.</p>
418      * @property defaultFormat
419      * @static
420      * @type String
421      */
422     defaultFormat : "m/d/Y",
423     /**
424      * Get the short month name for the given month number.
425      * Override this function for international dates.
426      * @param {Number} month A zero-based javascript month number.
427      * @return {String} The short month name.
428      * @static
429      */
430     getShortMonthName : function(month) {
431         return utilDate.monthNames[month].substring(0, 3);
432     },
433
434     /**
435      * Get the short day name for the given day number.
436      * Override this function for international dates.
437      * @param {Number} day A zero-based javascript day number.
438      * @return {String} The short day name.
439      * @static
440      */
441     getShortDayName : function(day) {
442         return utilDate.dayNames[day].substring(0, 3);
443     },
444
445     /**
446      * Get the zero-based javascript month number for the given short/full month name.
447      * Override this function for international dates.
448      * @param {String} name The short/full month name.
449      * @return {Number} The zero-based javascript month number.
450      * @static
451      */
452     getMonthNumber : function(name) {
453         // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive)
454         return utilDate.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
455     },
456
457     /**
458      * Checks if the specified format contains hour information
459      * @param {String} format The format to check
460      * @return {Boolean} True if the format contains hour information
461      * @static
462      */
463     formatContainsHourInfo : (function(){
464         var stripEscapeRe = /(\\.)/g,
465             hourInfoRe = /([gGhHisucUOPZ]|MS)/;
466         return function(format){
467             return hourInfoRe.test(format.replace(stripEscapeRe, ''));
468         };
469     })(),
470
471     /**
472      * Checks if the specified format contains information about
473      * anything other than the time.
474      * @param {String} format The format to check
475      * @return {Boolean} True if the format contains information about
476      * date/day information.
477      * @static
478      */
479     formatContainsDateInfo : (function(){
480         var stripEscapeRe = /(\\.)/g,
481             dateInfoRe = /([djzmnYycU]|MS)/;
482
483         return function(format){
484             return dateInfoRe.test(format.replace(stripEscapeRe, ''));
485         };
486     })(),
487
488     /**
489      * The base format-code to formatting-function hashmap used by the {@link #format} method.
490      * Formatting functions are strings (or functions which return strings) which
491      * will return the appropriate value when evaluated in the context of the Date object
492      * from which the {@link #format} method is called.
493      * Add to / override these mappings for custom date formatting.
494      * Note: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found.
495      * Example:
496      * <pre><code>
497 Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
498 console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
499 </code></pre>
500      * @type Object
501      * @static
502      */
503     formatCodes : {
504         d: "Ext.String.leftPad(this.getDate(), 2, '0')",
505         D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name
506         j: "this.getDate()",
507         l: "Ext.Date.dayNames[this.getDay()]",
508         N: "(this.getDay() ? this.getDay() : 7)",
509         S: "Ext.Date.getSuffix(this)",
510         w: "this.getDay()",
511         z: "Ext.Date.getDayOfYear(this)",
512         W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')",
513         F: "Ext.Date.monthNames[this.getMonth()]",
514         m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')",
515         M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name
516         n: "(this.getMonth() + 1)",
517         t: "Ext.Date.getDaysInMonth(this)",
518         L: "(Ext.Date.isLeapYear(this) ? 1 : 0)",
519         o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",
520         Y: "Ext.String.leftPad(this.getFullYear(), 4, '0')",
521         y: "('' + this.getFullYear()).substring(2, 4)",
522         a: "(this.getHours() < 12 ? 'am' : 'pm')",
523         A: "(this.getHours() < 12 ? 'AM' : 'PM')",
524         g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
525         G: "this.getHours()",
526         h: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
527         H: "Ext.String.leftPad(this.getHours(), 2, '0')",
528         i: "Ext.String.leftPad(this.getMinutes(), 2, '0')",
529         s: "Ext.String.leftPad(this.getSeconds(), 2, '0')",
530         u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')",
531         O: "Ext.Date.getGMTOffset(this)",
532         P: "Ext.Date.getGMTOffset(this, true)",
533         T: "Ext.Date.getTimezone(this)",
534         Z: "(this.getTimezoneOffset() * -60)",
535
536         c: function() { // ISO-8601 -- GMT format
537             for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
538                 var e = c.charAt(i);
539                 code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal
540             }
541             return code.join(" + ");
542         },
543         /*
544         c: function() { // ISO-8601 -- UTC format
545             return [
546               "this.getUTCFullYear()", "'-'",
547               "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
548               "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')",
549               "'T'",
550               "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'",
551               "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
552               "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')",
553               "'Z'"
554             ].join(" + ");
555         },
556         */
557
558         U: "Math.round(this.getTime() / 1000)"
559     },
560
561     /**
562      * Checks if the passed Date parameters will cause a javascript Date "rollover".
563      * @param {Number} year 4-digit year
564      * @param {Number} month 1-based month-of-year
565      * @param {Number} day Day of month
566      * @param {Number} hour (optional) Hour
567      * @param {Number} minute (optional) Minute
568      * @param {Number} second (optional) Second
569      * @param {Number} millisecond (optional) Millisecond
570      * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
571      * @static
572      */
573     isValid : function(y, m, d, h, i, s, ms) {
574         // setup defaults
575         h = h || 0;
576         i = i || 0;
577         s = s || 0;
578         ms = ms || 0;
579
580         // Special handling for year < 100
581         var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.YEAR, y < 100 ? y - 100 : 0);
582
583         return y == dt.getFullYear() &&
584             m == dt.getMonth() + 1 &&
585             d == dt.getDate() &&
586             h == dt.getHours() &&
587             i == dt.getMinutes() &&
588             s == dt.getSeconds() &&
589             ms == dt.getMilliseconds();
590     },
591
592     /**
593      * Parses the passed string using the specified date format.
594      * Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
595      * The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
596      * which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
597      * the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
598      * Keep in mind that the input date string must precisely match the specified format string
599      * in order for the parse operation to be successful (failed parse operations return a null value).
600      * <p>Example:</p><pre><code>
601 //dt = Fri May 25 2007 (current date)
602 var dt = new Date();
603
604 //dt = Thu May 25 2006 (today&#39;s month/day in 2006)
605 dt = Ext.Date.parse("2006", "Y");
606
607 //dt = Sun Jan 15 2006 (all date parts specified)
608 dt = Ext.Date.parse("2006-01-15", "Y-m-d");
609
610 //dt = Sun Jan 15 2006 15:20:01
611 dt = Ext.Date.parse("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
612
613 // attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
614 dt = Ext.Date.parse("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
615 </code></pre>
616      * @param {String} input The raw date string.
617      * @param {String} format The expected date string format.
618      * @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
619                         (defaults to false). Invalid date strings will return null when parsed.
620      * @return {Date} The parsed Date.
621      * @static
622      */
623     parse : function(input, format, strict) {
624         var p = utilDate.parseFunctions;
625         if (p[format] == null) {
626             utilDate.createParser(format);
627         }
628         return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict);
629     },
630
631     // Backwards compat
632     parseDate: function(input, format, strict){
633         return utilDate.parse(input, format, strict);
634     },
635
636
637     // private
638     getFormatCode : function(character) {
639         var f = utilDate.formatCodes[character];
640
641         if (f) {
642           f = typeof f == 'function'? f() : f;
643           utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution
644         }
645
646         // note: unknown characters are treated as literals
647         return f || ("'" + Ext.String.escape(character) + "'");
648     },
649
650     // private
651     createFormat : function(format) {
652         var code = [],
653             special = false,
654             ch = '';
655
656         for (var i = 0; i < format.length; ++i) {
657             ch = format.charAt(i);
658             if (!special && ch == "\\") {
659                 special = true;
660             } else if (special) {
661                 special = false;
662                 code.push("'" + Ext.String.escape(ch) + "'");
663             } else {
664                 code.push(utilDate.getFormatCode(ch));
665             }
666         }
667         utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+'));
668     },
669
670     // private
671     createParser : (function() {
672         var code = [
673             "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
674                 "def = Ext.Date.defaults,",
675                 "results = String(input).match(Ext.Date.parseRegexes[{0}]);", // either null, or an array of matched strings
676
677             "if(results){",
678                 "{1}",
679
680                 "if(u != null){", // i.e. unix time is defined
681                     "v = new Date(u * 1000);", // give top priority to UNIX time
682                 "}else{",
683                     // create Date object representing midnight of the current day;
684                     // this will provide us with our date defaults
685                     // (note: clearTime() handles Daylight Saving Time automatically)
686                     "dt = Ext.Date.clearTime(new Date);",
687
688                     // date calculations (note: these calculations create a dependency on Ext.Number.from())
689                     "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));",
690                     "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));",
691                     "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));",
692
693                     // time calculations (note: these calculations create a dependency on Ext.Number.from())
694                     "h  = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));",
695                     "i  = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));",
696                     "s  = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));",
697                     "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));",
698
699                     "if(z >= 0 && y >= 0){",
700                         // both the year and zero-based day of year are defined and >= 0.
701                         // these 2 values alone provide sufficient info to create a full date object
702
703                         // create Date object representing January 1st for the given year
704                         // handle years < 100 appropriately
705                         "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
706
707                         // then add day of year, checking for Date "rollover" if necessary
708                         "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);",
709                     "}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
710                         "v = null;", // invalid date, so return null
711                     "}else{",
712                         // plain old Date object
713                         // handle years < 100 properly
714                         "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
715                     "}",
716                 "}",
717             "}",
718
719             "if(v){",
720                 // favour UTC offset over GMT offset
721                 "if(zz != null){",
722                     // reset to UTC, then add offset
723                     "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
724                 "}else if(o){",
725                     // reset to GMT, then add offset
726                     "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
727                 "}",
728             "}",
729
730             "return v;"
731         ].join('\n');
732
733         return function(format) {
734             var regexNum = utilDate.parseRegexes.length,
735                 currentGroup = 1,
736                 calc = [],
737                 regex = [],
738                 special = false,
739                 ch = "";
740
741             for (var i = 0; i < format.length; ++i) {
742                 ch = format.charAt(i);
743                 if (!special && ch == "\\") {
744                     special = true;
745                 } else if (special) {
746                     special = false;
747                     regex.push(Ext.String.escape(ch));
748                 } else {
749                     var obj = utilDate.formatCodeToRegex(ch, currentGroup);
750                     currentGroup += obj.g;
751                     regex.push(obj.s);
752                     if (obj.g && obj.c) {
753                         calc.push(obj.c);
754                     }
755                 }
756             }
757
758             utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
759             utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join('')));
760         };
761     })(),
762
763     // private
764     parseCodes : {
765         /*
766          * Notes:
767          * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
768          * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
769          * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
770          */
771         d: {
772             g:1,
773             c:"d = parseInt(results[{0}], 10);\n",
774             s:"(\\d{2})" // day of month with leading zeroes (01 - 31)
775         },
776         j: {
777             g:1,
778             c:"d = parseInt(results[{0}], 10);\n",
779             s:"(\\d{1,2})" // day of month without leading zeroes (1 - 31)
780         },
781         D: function() {
782             for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names
783             return {
784                 g:0,
785                 c:null,
786                 s:"(?:" + a.join("|") +")"
787             };
788         },
789         l: function() {
790             return {
791                 g:0,
792                 c:null,
793                 s:"(?:" + utilDate.dayNames.join("|") + ")"
794             };
795         },
796         N: {
797             g:0,
798             c:null,
799             s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
800         },
801         S: {
802             g:0,
803             c:null,
804             s:"(?:st|nd|rd|th)"
805         },
806         w: {
807             g:0,
808             c:null,
809             s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
810         },
811         z: {
812             g:1,
813             c:"z = parseInt(results[{0}], 10);\n",
814             s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
815         },
816         W: {
817             g:0,
818             c:null,
819             s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)
820         },
821         F: function() {
822             return {
823                 g:1,
824                 c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
825                 s:"(" + utilDate.monthNames.join("|") + ")"
826             };
827         },
828         M: function() {
829             for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names
830             return Ext.applyIf({
831                 s:"(" + a.join("|") + ")"
832             }, utilDate.formatCodeToRegex("F"));
833         },
834         m: {
835             g:1,
836             c:"m = parseInt(results[{0}], 10) - 1;\n",
837             s:"(\\d{2})" // month number with leading zeros (01 - 12)
838         },
839         n: {
840             g:1,
841             c:"m = parseInt(results[{0}], 10) - 1;\n",
842             s:"(\\d{1,2})" // month number without leading zeros (1 - 12)
843         },
844         t: {
845             g:0,
846             c:null,
847             s:"(?:\\d{2})" // no. of days in the month (28 - 31)
848         },
849         L: {
850             g:0,
851             c:null,
852             s:"(?:1|0)"
853         },
854         o: function() {
855             return utilDate.formatCodeToRegex("Y");
856         },
857         Y: {
858             g:1,
859             c:"y = parseInt(results[{0}], 10);\n",
860             s:"(\\d{4})" // 4-digit year
861         },
862         y: {
863             g:1,
864             c:"var ty = parseInt(results[{0}], 10);\n"
865                 + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
866             s:"(\\d{1,2})"
867         },
868         /**
869          * In the am/pm parsing routines, we allow both upper and lower case
870          * even though it doesn't exactly match the spec. It gives much more flexibility
871          * in being able to specify case insensitive regexes.
872          */
873         a: {
874             g:1,
875             c:"if (/(am)/i.test(results[{0}])) {\n"
876                 + "if (!h || h == 12) { h = 0; }\n"
877                 + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
878             s:"(am|pm|AM|PM)"
879         },
880         A: {
881             g:1,
882             c:"if (/(am)/i.test(results[{0}])) {\n"
883                 + "if (!h || h == 12) { h = 0; }\n"
884                 + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
885             s:"(AM|PM|am|pm)"
886         },
887         g: function() {
888             return utilDate.formatCodeToRegex("G");
889         },
890         G: {
891             g:1,
892             c:"h = parseInt(results[{0}], 10);\n",
893             s:"(\\d{1,2})" // 24-hr format of an hour without leading zeroes (0 - 23)
894         },
895         h: function() {
896             return utilDate.formatCodeToRegex("H");
897         },
898         H: {
899             g:1,
900             c:"h = parseInt(results[{0}], 10);\n",
901             s:"(\\d{2})" //  24-hr format of an hour with leading zeroes (00 - 23)
902         },
903         i: {
904             g:1,
905             c:"i = parseInt(results[{0}], 10);\n",
906             s:"(\\d{2})" // minutes with leading zeros (00 - 59)
907         },
908         s: {
909             g:1,
910             c:"s = parseInt(results[{0}], 10);\n",
911             s:"(\\d{2})" // seconds with leading zeros (00 - 59)
912         },
913         u: {
914             g:1,
915             c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
916             s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
917         },
918         O: {
919             g:1,
920             c:[
921                 "o = results[{0}];",
922                 "var sn = o.substring(0,1),", // get + / - sign
923                     "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
924                     "mn = o.substring(3,5) % 60;", // get minutes
925                 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
926             ].join("\n"),
927             s: "([+\-]\\d{4})" // GMT offset in hrs and mins
928         },
929         P: {
930             g:1,
931             c:[
932                 "o = results[{0}];",
933                 "var sn = o.substring(0,1),", // get + / - sign
934                     "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
935                     "mn = o.substring(4,6) % 60;", // get minutes
936                 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
937             ].join("\n"),
938             s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
939         },
940         T: {
941             g:0,
942             c:null,
943             s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
944         },
945         Z: {
946             g:1,
947             c:"zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
948                   + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
949             s:"([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
950         },
951         c: function() {
952             var calc = [],
953                 arr = [
954                     utilDate.formatCodeToRegex("Y", 1), // year
955                     utilDate.formatCodeToRegex("m", 2), // month
956                     utilDate.formatCodeToRegex("d", 3), // day
957                     utilDate.formatCodeToRegex("h", 4), // hour
958                     utilDate.formatCodeToRegex("i", 5), // minute
959                     utilDate.formatCodeToRegex("s", 6), // second
960                     {c:"ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n"}, // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
961                     {c:[ // allow either "Z" (i.e. UTC) or "-0530" or "+08:00" (i.e. UTC offset) timezone delimiters. assumes local timezone if no timezone is specified
962                         "if(results[8]) {", // timezone specified
963                             "if(results[8] == 'Z'){",
964                                 "zz = 0;", // UTC
965                             "}else if (results[8].indexOf(':') > -1){",
966                                 utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator
967                             "}else{",
968                                 utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator
969                             "}",
970                         "}"
971                     ].join('\n')}
972                 ];
973
974             for (var i = 0, l = arr.length; i < l; ++i) {
975                 calc.push(arr[i].c);
976             }
977
978             return {
979                 g:1,
980                 c:calc.join(""),
981                 s:[
982                     arr[0].s, // year (required)
983                     "(?:", "-", arr[1].s, // month (optional)
984                         "(?:", "-", arr[2].s, // day (optional)
985                             "(?:",
986                                 "(?:T| )?", // time delimiter -- either a "T" or a single blank space
987                                 arr[3].s, ":", arr[4].s,  // hour AND minute, delimited by a single colon (optional). MUST be preceded by either a "T" or a single blank space
988                                 "(?::", arr[5].s, ")?", // seconds (optional)
989                                 "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
990                                 "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
991                             ")?",
992                         ")?",
993                     ")?"
994                 ].join("")
995             };
996         },
997         U: {
998             g:1,
999             c:"u = parseInt(results[{0}], 10);\n",
1000             s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
1001         }
1002     },
1003
1004     //Old Ext.Date prototype methods.
1005     // private
1006     dateFormat: function(date, format) {
1007         return utilDate.format(date, format);
1008     },
1009
1010     /**
1011      * Formats a date given the supplied format string.
1012      * @param {Date} date The date to format
1013      * @param {String} format The format string
1014      * @return {String} The formatted date
1015      */
1016     format: function(date, format) {
1017         if (utilDate.formatFunctions[format] == null) {
1018             utilDate.createFormat(format);
1019         }
1020         var result = utilDate.formatFunctions[format].call(date);
1021         return result + '';
1022     },
1023
1024     /**
1025      * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1026      *
1027      * Note: The date string returned by the javascript Date object's toString() method varies
1028      * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
1029      * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
1030      * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
1031      * (which may or may not be present), failing which it proceeds to get the timezone abbreviation
1032      * from the GMT offset portion of the date string.
1033      * @param {Date} date The date
1034      * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
1035      */
1036     getTimezone : function(date) {
1037         // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
1038         //
1039         // Opera  : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
1040         // Safari : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone (same as FF)
1041         // FF     : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
1042         // IE     : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
1043         // IE     : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
1044         //
1045         // this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
1046         // step 1: (?:\((.*)\) -- find timezone in parentheses
1047         // step 2: ([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?) -- if nothing was found in step 1, find timezone from timezone offset portion of date string
1048         // step 3: remove all non uppercase characters found in step 1 and 2
1049         return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
1050     },
1051
1052     /**
1053      * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1054      * @param {Date} date The date
1055      * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
1056      * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
1057      */
1058     getGMTOffset : function(date, colon) {
1059         var offset = date.getTimezoneOffset();
1060         return (offset > 0 ? "-" : "+")
1061             + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0")
1062             + (colon ? ":" : "")
1063             + Ext.String.leftPad(Math.abs(offset % 60), 2, "0");
1064     },
1065
1066     /**
1067      * Get the numeric day number of the year, adjusted for leap year.
1068      * @param {Date} date The date
1069      * @return {Number} 0 to 364 (365 in leap years).
1070      */
1071     getDayOfYear: function(date) {
1072         var num = 0,
1073             d = Ext.Date.clone(date),
1074             m = date.getMonth(),
1075             i;
1076
1077         for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
1078             num += utilDate.getDaysInMonth(d);
1079         }
1080         return num + date.getDate() - 1;
1081     },
1082
1083     /**
1084      * Get the numeric ISO-8601 week number of the year.
1085      * (equivalent to the format specifier 'W', but without a leading zero).
1086      * @param {Date} date The date
1087      * @return {Number} 1 to 53
1088      */
1089     getWeekOfYear : (function() {
1090         // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
1091         var ms1d = 864e5, // milliseconds in a day
1092             ms7d = 7 * ms1d; // milliseconds in a week
1093
1094         return function(date) { // return a closure so constants get calculated only once
1095             var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number
1096                 AWN = Math.floor(DC3 / 7), // an Absolute Week Number
1097                 Wyr = new Date(AWN * ms7d).getUTCFullYear();
1098
1099             return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
1100         };
1101     })(),
1102
1103     /**
1104      * Checks if the current date falls within a leap year.
1105      * @param {Date} date The date
1106      * @return {Boolean} True if the current date falls within a leap year, false otherwise.
1107      */
1108     isLeapYear : function(date) {
1109         var year = date.getFullYear();
1110         return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1111     },
1112
1113     /**
1114      * Get the first day of the current month, adjusted for leap year.  The returned value
1115      * is the numeric day index within the week (0-6) which can be used in conjunction with
1116      * the {@link #monthNames} array to retrieve the textual day name.
1117      * Example:
1118      * <pre><code>
1119 var dt = new Date('1/10/2007'),
1120     firstDay = Ext.Date.getFirstDayOfMonth(dt);
1121 console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
1122      * </code></pre>
1123      * @param {Date} date The date
1124      * @return {Number} The day number (0-6).
1125      */
1126     getFirstDayOfMonth : function(date) {
1127         var day = (date.getDay() - (date.getDate() - 1)) % 7;
1128         return (day < 0) ? (day + 7) : day;
1129     },
1130
1131     /**
1132      * Get the last day of the current month, adjusted for leap year.  The returned value
1133      * is the numeric day index within the week (0-6) which can be used in conjunction with
1134      * the {@link #monthNames} array to retrieve the textual day name.
1135      * Example:
1136      * <pre><code>
1137 var dt = new Date('1/10/2007'),
1138     lastDay = Ext.Date.getLastDayOfMonth(dt);
1139 console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
1140      * </code></pre>
1141      * @param {Date} date The date
1142      * @return {Number} The day number (0-6).
1143      */
1144     getLastDayOfMonth : function(date) {
1145         return utilDate.getLastDateOfMonth(date).getDay();
1146     },
1147
1148
1149     /**
1150      * Get the date of the first day of the month in which this date resides.
1151      * @param {Date} date The date
1152      * @return {Date}
1153      */
1154     getFirstDateOfMonth : function(date) {
1155         return new Date(date.getFullYear(), date.getMonth(), 1);
1156     },
1157
1158     /**
1159      * Get the date of the last day of the month in which this date resides.
1160      * @param {Date} date The date
1161      * @return {Date}
1162      */
1163     getLastDateOfMonth : function(date) {
1164         return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date));
1165     },
1166
1167     /**
1168      * Get the number of days in the current month, adjusted for leap year.
1169      * @param {Date} date The date
1170      * @return {Number} The number of days in the month.
1171      */
1172     getDaysInMonth: (function() {
1173         var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
1174
1175         return function(date) { // return a closure for efficiency
1176             var m = date.getMonth();
1177
1178             return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m];
1179         };
1180     })(),
1181
1182     /**
1183      * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1184      * @param {Date} date The date
1185      * @return {String} 'st, 'nd', 'rd' or 'th'.
1186      */
1187     getSuffix : function(date) {
1188         switch (date.getDate()) {
1189             case 1:
1190             case 21:
1191             case 31:
1192                 return "st";
1193             case 2:
1194             case 22:
1195                 return "nd";
1196             case 3:
1197             case 23:
1198                 return "rd";
1199             default:
1200                 return "th";
1201         }
1202     },
1203
1204     /**
1205      * Creates and returns a new Date instance with the exact same date value as the called instance.
1206      * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1207      * variable will also be changed.  When the intention is to create a new variable that will not
1208      * modify the original instance, you should create a clone.
1209      *
1210      * Example of correctly cloning a date:
1211      * <pre><code>
1212 //wrong way:
1213 var orig = new Date('10/1/2006');
1214 var copy = orig;
1215 copy.setDate(5);
1216 console.log(orig);  //returns 'Thu Oct 05 2006'!
1217
1218 //correct way:
1219 var orig = new Date('10/1/2006'),
1220     copy = Ext.Date.clone(orig);
1221 copy.setDate(5);
1222 console.log(orig);  //returns 'Thu Oct 01 2006'
1223      * </code></pre>
1224      * @param {Date} date The date
1225      * @return {Date} The new Date instance.
1226      */
1227     clone : function(date) {
1228         return new Date(date.getTime());
1229     },
1230
1231     /**
1232      * Checks if the current date is affected by Daylight Saving Time (DST).
1233      * @param {Date} date The date
1234      * @return {Boolean} True if the current date is affected by DST.
1235      */
1236     isDST : function(date) {
1237         // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172
1238         // courtesy of @geoffrey.mcgill
1239         return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset();
1240     },
1241
1242     /**
1243      * Attempts to clear all time information from this Date by setting the time to midnight of the same day,
1244      * automatically adjusting for Daylight Saving Time (DST) where applicable.
1245      * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
1246      * @param {Date} date The date
1247      * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
1248      * @return {Date} this or the clone.
1249      */
1250     clearTime : function(date, clone) {
1251         if (clone) {
1252             return Ext.Date.clearTime(Ext.Date.clone(date));
1253         }
1254
1255         // get current date before clearing time
1256         var d = date.getDate();
1257
1258         // clear time
1259         date.setHours(0);
1260         date.setMinutes(0);
1261         date.setSeconds(0);
1262         date.setMilliseconds(0);
1263
1264         if (date.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
1265             // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
1266             // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
1267
1268             // increment hour until cloned date == current date
1269             for (var hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr));
1270
1271             date.setDate(d);
1272             date.setHours(c.getHours());
1273         }
1274
1275         return date;
1276     },
1277
1278     /**
1279      * Provides a convenient method for performing basic date arithmetic. This method
1280      * does not modify the Date instance being called - it creates and returns
1281      * a new Date instance containing the resulting date value.
1282      *
1283      * Examples:
1284      * <pre><code>
1285 // Basic usage:
1286 var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
1287 console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
1288
1289 // Negative values will be subtracted:
1290 var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
1291 console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1292
1293      * </code></pre>
1294      *
1295      * @param {Date} date The date to modify
1296      * @param {String} interval A valid date interval enum value.
1297      * @param {Number} value The amount to add to the current date.
1298      * @return {Date} The new Date instance.
1299      */
1300     add : function(date, interval, value) {
1301         var d = Ext.Date.clone(date),
1302             Date = Ext.Date;
1303         if (!interval || value === 0) return d;
1304
1305         switch(interval.toLowerCase()) {
1306             case Ext.Date.MILLI:
1307                 d.setMilliseconds(d.getMilliseconds() + value);
1308                 break;
1309             case Ext.Date.SECOND:
1310                 d.setSeconds(d.getSeconds() + value);
1311                 break;
1312             case Ext.Date.MINUTE:
1313                 d.setMinutes(d.getMinutes() + value);
1314                 break;
1315             case Ext.Date.HOUR:
1316                 d.setHours(d.getHours() + value);
1317                 break;
1318             case Ext.Date.DAY:
1319                 d.setDate(d.getDate() + value);
1320                 break;
1321             case Ext.Date.MONTH:
1322                 var day = date.getDate();
1323                 if (day > 28) {
1324                     day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), 'mo', value)).getDate());
1325                 }
1326                 d.setDate(day);
1327                 d.setMonth(date.getMonth() + value);
1328                 break;
1329             case Ext.Date.YEAR:
1330                 d.setFullYear(date.getFullYear() + value);
1331                 break;
1332         }
1333         return d;
1334     },
1335
1336     /**
1337      * Checks if a date falls on or between the given start and end dates.
1338      * @param {Date} date The date to check
1339      * @param {Date} start Start date
1340      * @param {Date} end End date
1341      * @return {Boolean} true if this date falls on or between the given start and end dates.
1342      */
1343     between : function(date, start, end) {
1344         var t = date.getTime();
1345         return start.getTime() <= t && t <= end.getTime();
1346     },
1347
1348     //Maintains compatibility with old static and prototype window.Date methods.
1349     compat: function() {
1350         var nativeDate = window.Date,
1351             p, u,
1352             statics = ['useStrict', 'formatCodeToRegex', 'parseFunctions', 'parseRegexes', 'formatFunctions', 'y2kYear', 'MILLI', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR', 'defaults', 'dayNames', 'monthNames', 'monthNumbers', 'getShortMonthName', 'getShortDayName', 'getMonthNumber', 'formatCodes', 'isValid', 'parseDate', 'getFormatCode', 'createFormat', 'createParser', 'parseCodes'],
1353             proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'];
1354
1355         //Append statics
1356         Ext.Array.forEach(statics, function(s) {
1357             nativeDate[s] = utilDate[s];
1358         });
1359
1360         //Append to prototype
1361         Ext.Array.forEach(proto, function(s) {
1362             nativeDate.prototype[s] = function() {
1363                 var args = Array.prototype.slice.call(arguments);
1364                 args.unshift(this);
1365                 return utilDate[s].apply(utilDate, args);
1366             };
1367         });
1368     }
1369 };
1370
1371 var utilDate = Ext.Date;
1372
1373 })();