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