provide installation instructions
[extjs.git] / source / util / Date.js
1 /*\r
2  * Ext JS Library 2.2.1\r
3  * Copyright(c) 2006-2009, Ext JS, LLC.\r
4  * licensing@extjs.com\r
5  * \r
6  * http://extjs.com/license\r
7  */\r
8 \r
9 /**\r
10  * @class Date\r
11  *\r
12  * The date parsing and format syntax is a subset of\r
13  * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are\r
14  * supported will provide results equivalent to their PHP versions.\r
15  *\r
16  * The following is a list of all currently supported formats:\r
17  *<pre>\r
18 Format  Description                                                               Example returned values\r
19 ------  -----------------------------------------------------------------------   -----------------------\r
20   d     Day of the month, 2 digits with leading zeros                             01 to 31\r
21   D     A short textual representation of the day of the week                     Mon to Sun\r
22   j     Day of the month without leading zeros                                    1 to 31\r
23   l     A full textual representation of the day of the week                      Sunday to Saturday\r
24   N     ISO-8601 numeric representation of the day of the week                    1 (for Monday) through 7 (for Sunday)\r
25   S     English ordinal suffix for the day of the month, 2 characters             st, nd, rd or th. Works well with j\r
26   w     Numeric representation of the day of the week                             0 (for Sunday) to 6 (for Saturday)\r
27   z     The day of the year (starting from 0)                                     0 to 364 (365 in leap years)\r
28   W     ISO-8601 week number of year, weeks starting on Monday                    01 to 53\r
29   F     A full textual representation of a month, such as January or March        January to December\r
30   m     Numeric representation of a month, with leading zeros                     01 to 12\r
31   M     A short textual representation of a month                                 Jan to Dec\r
32   n     Numeric representation of a month, without leading zeros                  1 to 12\r
33   t     Number of days in the given month                                         28 to 31\r
34   L     Whether it's a leap year                                                  1 if it is a leap year, 0 otherwise.\r
35   o     ISO-8601 year number (identical to (Y), but if the ISO week number (W)    Examples: 1998 or 2004\r
36         belongs to the previous or next year, that year is used instead)\r
37   Y     A full numeric representation of a year, 4 digits                         Examples: 1999 or 2003\r
38   y     A two digit representation of a year                                      Examples: 99 or 03\r
39   a     Lowercase Ante meridiem and Post meridiem                                 am or pm\r
40   A     Uppercase Ante meridiem and Post meridiem                                 AM or PM\r
41   g     12-hour format of an hour without leading zeros                           1 to 12\r
42   G     24-hour format of an hour without leading zeros                           0 to 23\r
43   h     12-hour format of an hour with leading zeros                              01 to 12\r
44   H     24-hour format of an hour with leading zeros                              00 to 23\r
45   i     Minutes, with leading zeros                                               00 to 59\r
46   s     Seconds, with leading zeros                                               00 to 59\r
47   u     Decimal fraction of a second                                              Examples:\r
48         (minimum 1 digit, arbitrary number of digits allowed)                     001 (i.e. 0.001s) or\r
49                                                                                   100 (i.e. 0.100s) or\r
50                                                                                   999 (i.e. 0.999s) or\r
51                                                                                   999876543210 (i.e. 0.999876543210s)\r
52   O     Difference to Greenwich time (GMT) in hours and minutes                   Example: +1030\r
53   P     Difference to Greenwich time (GMT) with colon between hours and minutes   Example: -08:00\r
54   T     Timezone abbreviation of the machine running the code                     Examples: EST, MDT, PDT ...\r
55   Z     Timezone offset in seconds (negative if west of UTC, positive if east)    -43200 to 50400\r
56   c     ISO 8601 date (note: the decimal fraction of a second, if specified,      Examples:\r
57         must contain at least 1 digit. There is no limit on the maximum number    2007-04-17T15:19:21+08:00 or\r
58         of digits allowed. see http://www.w3.org/TR/NOTE-datetime for more info)  2008-03-16T16:18:22Z or\r
59                                                                                   2009-02-15T17:17:23.9+01:00 or\r
60                                                                                   2010-01-14T18:16:24,999876543-07:00\r
61   U     Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)                1193432466 or -2138434463\r
62 </pre>\r
63  *\r
64  * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):\r
65  * <pre><code>\r
66 // Sample date:\r
67 // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'\r
68 \r
69 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');\r
70 document.write(dt.format('Y-m-d'));                           // 2007-01-10\r
71 document.write(dt.format('F j, Y, g:i a'));                   // January 10, 2007, 3:05 pm\r
72 document.write(dt.format('l, \\t\\he jS \\of F Y h:i:s A'));  // Wednesday, the 10th of January 2007 03:05:01 PM\r
73  </code></pre>\r
74  *\r
75  * Here are some standard date/time patterns that you might find helpful.  They\r
76  * are not part of the source of Date.js, but to use them you can simply copy this\r
77  * block of code into any script that is included after Date.js and they will also become\r
78  * globally available on the Date object.  Feel free to add or remove patterns as needed in your code.\r
79  * <pre><code>\r
80 Date.patterns = {\r
81     ISO8601Long:"Y-m-d H:i:s",\r
82     ISO8601Short:"Y-m-d",\r
83     ShortDate: "n/j/Y",\r
84     LongDate: "l, F d, Y",\r
85     FullDateTime: "l, F d, Y g:i:s A",\r
86     MonthDay: "F d",\r
87     ShortTime: "g:i A",\r
88     LongTime: "g:i:s A",\r
89     SortableDateTime: "Y-m-d\\TH:i:s",\r
90     UniversalSortableDateTime: "Y-m-d H:i:sO",\r
91     YearMonth: "F, Y"\r
92 };\r
93 </code></pre>\r
94  *\r
95  * Example usage:\r
96  * <pre><code>\r
97 var dt = new Date();\r
98 document.write(dt.format(Date.patterns.ShortDate));\r
99  </code></pre>\r
100  */\r
101 \r
102 /*\r
103  * Most of the date-formatting functions below are the excellent work of Baron Schwartz.\r
104  * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)\r
105  * They generate precompiled functions from format patterns instead of parsing and\r
106  * processing each pattern every time a date is formatted. These functions are available\r
107  * on every Date object.\r
108  */\r
109 \r
110 (function() {\r
111 \r
112 // create private copy of Ext's String.format() method\r
113 // - to remove unnecessary dependency\r
114 // - to resolve namespace conflict with M$-Ajax's implementation\r
115 function xf(format) {\r
116     var args = Array.prototype.slice.call(arguments, 1);\r
117     return format.replace(/\{(\d+)\}/g, function(m, i) {\r
118         return args[i];\r
119     });\r
120 }\r
121 \r
122 \r
123 // private\r
124 Date.formatCodeToRegex = function(character, currentGroup) {\r
125     // Note: currentGroup - position in regex result array (see notes for Date.parseCodes below)\r
126     var p = Date.parseCodes[character];\r
127 \r
128     if (p) {\r
129       p = Ext.type(p) == 'function'? p() : p;\r
130       Date.parseCodes[character] = p; // reassign function result to prevent repeated execution\r
131     }\r
132 \r
133     return p? Ext.applyIf({\r
134       c: p.c? xf(p.c, currentGroup || "{0}") : p.c\r
135     }, p) : {\r
136         g:0,\r
137         c:null,\r
138         s:Ext.escapeRe(character) // treat unrecognised characters as literals\r
139     }\r
140 }\r
141 \r
142 // private shorthand for Date.formatCodeToRegex since we'll be using it fairly often\r
143 var $f = Date.formatCodeToRegex;\r
144 \r
145 Ext.apply(Date, {\r
146     // private\r
147     parseFunctions: {count:0},\r
148     parseRegexes: [],\r
149     formatFunctions: {count:0},\r
150     daysInMonth : [31,28,31,30,31,30,31,31,30,31,30,31],\r
151     y2kYear : 50,\r
152 \r
153     /**\r
154      * Date interval constant\r
155      * @static\r
156      * @type String\r
157      */\r
158     MILLI : "ms",\r
159 \r
160     /**\r
161      * Date interval constant\r
162      * @static\r
163      * @type String\r
164      */\r
165     SECOND : "s",\r
166 \r
167     /**\r
168      * Date interval constant\r
169      * @static\r
170      * @type String\r
171      */\r
172     MINUTE : "mi",\r
173 \r
174     /** Date interval constant\r
175      * @static\r
176      * @type String\r
177      */\r
178     HOUR : "h",\r
179 \r
180     /**\r
181      * Date interval constant\r
182      * @static\r
183      * @type String\r
184      */\r
185     DAY : "d",\r
186 \r
187     /**\r
188      * Date interval constant\r
189      * @static\r
190      * @type String\r
191      */\r
192     MONTH : "mo",\r
193 \r
194     /**\r
195      * Date interval constant\r
196      * @static\r
197      * @type String\r
198      */\r
199     YEAR : "y",\r
200 \r
201     /**\r
202      * An array of textual day names.\r
203      * Override these values for international dates.\r
204      * Example:\r
205      *<pre><code>\r
206     Date.dayNames = [\r
207       'SundayInYourLang',\r
208       'MondayInYourLang',\r
209       ...\r
210     ];\r
211     </code></pre>\r
212      * @type Array\r
213      * @static\r
214      */\r
215     dayNames : [\r
216         "Sunday",\r
217         "Monday",\r
218         "Tuesday",\r
219         "Wednesday",\r
220         "Thursday",\r
221         "Friday",\r
222         "Saturday"\r
223     ],\r
224 \r
225     /**\r
226      * An array of textual month names.\r
227      * Override these values for international dates.\r
228      * Example:\r
229      *<pre><code>\r
230     Date.monthNames = [\r
231       'JanInYourLang',\r
232       'FebInYourLang',\r
233       ...\r
234     ];\r
235     </code></pre>\r
236      * @type Array\r
237      * @static\r
238      */\r
239     monthNames : [\r
240         "January",\r
241         "February",\r
242         "March",\r
243         "April",\r
244         "May",\r
245         "June",\r
246         "July",\r
247         "August",\r
248         "September",\r
249         "October",\r
250         "November",\r
251         "December"\r
252     ],\r
253 \r
254     /**\r
255      * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).\r
256      * Override these values for international dates.\r
257      * Example:\r
258      *<pre><code>\r
259     Date.monthNumbers = {\r
260       'ShortJanNameInYourLang':0,\r
261       'ShortFebNameInYourLang':1,\r
262       ...\r
263     };\r
264     </code></pre>\r
265      * @type Object\r
266      * @static\r
267      */\r
268     monthNumbers : {\r
269         Jan:0,\r
270         Feb:1,\r
271         Mar:2,\r
272         Apr:3,\r
273         May:4,\r
274         Jun:5,\r
275         Jul:6,\r
276         Aug:7,\r
277         Sep:8,\r
278         Oct:9,\r
279         Nov:10,\r
280         Dec:11\r
281     },\r
282 \r
283     /**\r
284      * Get the short month name for the given month number.\r
285      * Override this function for international dates.\r
286      * @param {Number} month A zero-based javascript month number.\r
287      * @return {String} The short month name.\r
288      * @static\r
289      */\r
290     getShortMonthName : function(month) {\r
291         return Date.monthNames[month].substring(0, 3);\r
292     },\r
293 \r
294     /**\r
295      * Get the short day name for the given day number.\r
296      * Override this function for international dates.\r
297      * @param {Number} day A zero-based javascript day number.\r
298      * @return {String} The short day name.\r
299      * @static\r
300      */\r
301     getShortDayName : function(day) {\r
302         return Date.dayNames[day].substring(0, 3);\r
303     },\r
304 \r
305     /**\r
306      * Get the zero-based javascript month number for the given short/full month name.\r
307      * Override this function for international dates.\r
308      * @param {String} name The short/full month name.\r
309      * @return {Number} The zero-based javascript month number.\r
310      * @static\r
311      */\r
312     getMonthNumber : function(name) {\r
313         // handle camel casing for english month names (since the keys for the Date.monthNumbers hash are case sensitive)\r
314         return Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];\r
315     },\r
316 \r
317     /**\r
318      * The base format-code to formatting-function hashmap used by the {@link #format} method.\r
319      * Formatting functions are strings (or functions which return strings) which\r
320      * will return the appropriate value when evaluated in the context of the Date object\r
321      * from which the {@link #format} method is called.\r
322      * Add to / override these mappings for custom date formatting.\r
323      * Note: Date.format() treats characters as literals if an appropriate mapping cannot be found.\r
324      * Example:\r
325     <pre><code>\r
326     Date.formatCodes.x = "String.leftPad(this.getDate(), 2, '0')";\r
327     (new Date()).format("X"); // returns the current day of the month\r
328     </code></pre>\r
329      * @type Object\r
330      * @static\r
331      */\r
332     formatCodes : {\r
333         d: "String.leftPad(this.getDate(), 2, '0')",\r
334         D: "Date.getShortDayName(this.getDay())", // get localised short day name\r
335         j: "this.getDate()",\r
336         l: "Date.dayNames[this.getDay()]",\r
337         N: "(this.getDay() ? this.getDay() : 7)",\r
338         S: "this.getSuffix()",\r
339         w: "this.getDay()",\r
340         z: "this.getDayOfYear()",\r
341         W: "String.leftPad(this.getWeekOfYear(), 2, '0')",\r
342         F: "Date.monthNames[this.getMonth()]",\r
343         m: "String.leftPad(this.getMonth() + 1, 2, '0')",\r
344         M: "Date.getShortMonthName(this.getMonth())", // get localised short month name\r
345         n: "(this.getMonth() + 1)",\r
346         t: "this.getDaysInMonth()",\r
347         L: "(this.isLeapYear() ? 1 : 0)",\r
348         o: "(this.getFullYear() + (this.getWeekOfYear() == 1 && this.getMonth() > 0 ? +1 : (this.getWeekOfYear() >= 52 && this.getMonth() < 11 ? -1 : 0)))",\r
349         Y: "this.getFullYear()",\r
350         y: "('' + this.getFullYear()).substring(2, 4)",\r
351         a: "(this.getHours() < 12 ? 'am' : 'pm')",\r
352         A: "(this.getHours() < 12 ? 'AM' : 'PM')",\r
353         g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",\r
354         G: "this.getHours()",\r
355         h: "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",\r
356         H: "String.leftPad(this.getHours(), 2, '0')",\r
357         i: "String.leftPad(this.getMinutes(), 2, '0')",\r
358         s: "String.leftPad(this.getSeconds(), 2, '0')",\r
359         u: "String.leftPad(this.getMilliseconds(), 3, '0')",\r
360         O: "this.getGMTOffset()",\r
361         P: "this.getGMTOffset(true)",\r
362         T: "this.getTimezone()",\r
363         Z: "(this.getTimezoneOffset() * -60)",\r
364         c: function() { // ISO-8601 -- GMT format\r
365             for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {\r
366                 var e = c.charAt(i);\r
367                 code.push(e == "T" ? "'T'" : Date.getFormatCode(e)); // treat T as a character literal\r
368             }\r
369             return code.join(" + ");\r
370         },\r
371         /*\r
372         c: function() { // ISO-8601 -- UTC format\r
373             return [\r
374               "this.getUTCFullYear()", "'-'",\r
375               "String.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",\r
376               "String.leftPad(this.getUTCDate(), 2, '0')",\r
377               "'T'",\r
378               "String.leftPad(this.getUTCHours(), 2, '0')", "':'",\r
379               "String.leftPad(this.getUTCMinutes(), 2, '0')", "':'",\r
380               "String.leftPad(this.getUTCSeconds(), 2, '0')",\r
381               "'Z'"\r
382             ].join(" + ");\r
383         },\r
384         */\r
385         U: "Math.round(this.getTime() / 1000)"\r
386     },\r
387 \r
388     /**\r
389      * Parses the passed string using the specified format. Note that this function expects dates in normal calendar\r
390      * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates.  Any part of\r
391      * the date format that is not specified will default to the current date value for that part.  Time parts can also\r
392      * be specified, but default to 0.  Keep in mind that the input date string must precisely match the specified format\r
393      * string or the parse operation will fail.\r
394      * Example Usage:\r
395      *<pre><code>\r
396     //dt = Fri May 25 2007 (current date)\r
397     var dt = new Date();\r
398 \r
399     //dt = Thu May 25 2006 (today's month/day in 2006)\r
400     dt = Date.parseDate("2006", "Y");\r
401 \r
402     //dt = Sun Jan 15 2006 (all date parts specified)\r
403     dt = Date.parseDate("2006-01-15", "Y-m-d");\r
404 \r
405     //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)\r
406     dt = Date.parseDate("2006-01-15 3:20:01 PM", "Y-m-d h:i:s A" );\r
407     </code></pre>\r
408      * @param {String} input The unparsed date as a string.\r
409      * @param {String} format The format the date is in.\r
410      * @return {Date} The parsed date.\r
411      * @static\r
412      */\r
413     parseDate : function(input, format) {\r
414         var p = Date.parseFunctions;\r
415         if (p[format] == null) {\r
416             Date.createParser(format);\r
417         }\r
418         var func = p[format];\r
419         return Date[func](input);\r
420     },\r
421 \r
422     // private\r
423     getFormatCode : function(character) {\r
424         var f = Date.formatCodes[character];\r
425 \r
426         if (f) {\r
427           f = Ext.type(f) == 'function'? f() : f;\r
428           Date.formatCodes[character] = f; // reassign function result to prevent repeated execution\r
429         }\r
430 \r
431         // note: unknown characters are treated as literals\r
432         return f || ("'" + String.escape(character) + "'");\r
433     },\r
434 \r
435     // private\r
436     createNewFormat : function(format) {\r
437         var funcName = "format" + Date.formatFunctions.count++,\r
438             code = "Date.prototype." + funcName + " = function(){return ",\r
439             special = false,\r
440             ch = '';\r
441 \r
442         Date.formatFunctions[format] = funcName;\r
443 \r
444         for (var i = 0; i < format.length; ++i) {\r
445             ch = format.charAt(i);\r
446             if (!special && ch == "\\") {\r
447                 special = true;\r
448             }\r
449             else if (special) {\r
450                 special = false;\r
451                 code += "'" + String.escape(ch) + "' + ";\r
452             }\r
453             else {\r
454                 code += Date.getFormatCode(ch) + " + ";\r
455             }\r
456         }\r
457         eval(code.substring(0, code.length - 3) + ";}");\r
458     },\r
459 \r
460     // private\r
461     createParser : function() {\r
462         var code = [\r
463             "Date.{0} = function(input){",\r
464                 "var y, m, d, h = 0, i = 0, s = 0, ms = 0, o, z, u, v;",\r
465                 "input = String(input);",\r
466                 "d = new Date();",\r
467                 "y = d.getFullYear();",\r
468                 "m = d.getMonth();",\r
469                 "d = d.getDate();",\r
470                 "var results = input.match(Date.parseRegexes[{1}]);",\r
471                 "if(results && results.length > 0){",\r
472                     "{2}",\r
473                     "if(u){",\r
474                         "v = new Date(u * 1000);", // give top priority to UNIX time\r
475                     "}else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0 && ms >= 0){",\r
476                         "v = new Date(y, m, d, h, i, s, ms);",\r
477                     "}else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0){",\r
478                         "v = new Date(y, m, d, h, i, s);",\r
479                     "}else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0){",\r
480                         "v = new Date(y, m, d, h, i);",\r
481                     "}else if (y >= 0 && m >= 0 && d > 0 && h >= 0){",\r
482                         "v = new Date(y, m, d, h);",\r
483                     "}else if (y >= 0 && m >= 0 && d > 0){",\r
484                         "v = new Date(y, m, d);",\r
485                     "}else if (y >= 0 && m >= 0){",\r
486                         "v = new Date(y, m);",\r
487                     "}else if (y >= 0){",\r
488                         "v = new Date(y);",\r
489                     "}",\r
490                 "}",\r
491                 "return (v && (z != null || o != null))?" // favour UTC offset over GMT offset\r
492                     + " (Ext.type(z) == 'number' ? v.add(Date.SECOND, -v.getTimezoneOffset() * 60 - z) :" // reset to UTC, then add offset\r
493                     + " v.add(Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn))) : v;", // reset to GMT, then add offset\r
494             "}"\r
495         ].join('\n');\r
496 \r
497         return function(format) {\r
498             var funcName = "parse" + Date.parseFunctions.count++,\r
499                 regexNum = Date.parseRegexes.length,\r
500                 currentGroup = 1,\r
501                 calc = "",\r
502                 regex = "",\r
503                 special = false,\r
504                 ch = "";\r
505 \r
506             Date.parseFunctions[format] = funcName;\r
507 \r
508             for (var i = 0; i < format.length; ++i) {\r
509                 ch = format.charAt(i);\r
510                 if (!special && ch == "\\") {\r
511                     special = true;\r
512                 }\r
513                 else if (special) {\r
514                     special = false;\r
515                     regex += String.escape(ch);\r
516                 }\r
517                 else {\r
518                     var obj = $f(ch, currentGroup);\r
519                     currentGroup += obj.g;\r
520                     regex += obj.s;\r
521                     if (obj.g && obj.c) {\r
522                         calc += obj.c;\r
523                     }\r
524                 }\r
525             }\r
526 \r
527             Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$", "i");\r
528             eval(xf(code, funcName, regexNum, calc));\r
529         }\r
530     }(),\r
531 \r
532     // private\r
533     parseCodes : {\r
534         /*\r
535          * Notes:\r
536          * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)\r
537          * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)\r
538          * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'\r
539          */\r
540         d: {\r
541             g:1,\r
542             c:"d = parseInt(results[{0}], 10);\n",\r
543             s:"(\\d{2})" // day of month with leading zeroes (01 - 31)\r
544         },\r
545         j: {\r
546             g:1,\r
547             c:"d = parseInt(results[{0}], 10);\n",\r
548             s:"(\\d{1,2})" // day of month without leading zeroes (1 - 31)\r
549         },\r
550         D: function() {\r
551             for (var a = [], i = 0; i < 7; a.push(Date.getShortDayName(i)), ++i); // get localised short day names\r
552             return {\r
553                 g:0,\r
554                 c:null,\r
555                 s:"(?:" + a.join("|") +")"\r
556             }\r
557         },\r
558         l: function() {\r
559             return {\r
560                 g:0,\r
561                 c:null,\r
562                 s:"(?:" + Date.dayNames.join("|") + ")"\r
563             }\r
564         },\r
565         N: {\r
566             g:0,\r
567             c:null,\r
568             s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))\r
569         },\r
570         S: {\r
571             g:0,\r
572             c:null,\r
573             s:"(?:st|nd|rd|th)"\r
574         },\r
575         w: {\r
576             g:0,\r
577             c:null,\r
578             s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))\r
579         },\r
580         z: {\r
581             g:0,\r
582             c:null,\r
583             s:"(?:\\d{1,3})" // day of the year (0 - 364 (365 in leap years))\r
584         },\r
585         W: {\r
586             g:0,\r
587             c:null,\r
588             s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)\r
589         },\r
590         F: function() {\r
591             return {\r
592                 g:1,\r
593                 c:"m = parseInt(Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number\r
594                 s:"(" + Date.monthNames.join("|") + ")"\r
595             }\r
596         },\r
597         M: function() {\r
598             for (var a = [], i = 0; i < 12; a.push(Date.getShortMonthName(i)), ++i); // get localised short month names\r
599             return Ext.applyIf({\r
600                 s:"(" + a.join("|") + ")"\r
601             }, $f("F"));\r
602         },\r
603         m: {\r
604             g:1,\r
605             c:"m = parseInt(results[{0}], 10) - 1;\n",\r
606             s:"(\\d{2})" // month number with leading zeros (01 - 12)\r
607         },\r
608         n: {\r
609             g:1,\r
610             c:"m = parseInt(results[{0}], 10) - 1;\n",\r
611             s:"(\\d{1,2})" // month number without leading zeros (1 - 12)\r
612         },\r
613         t: {\r
614             g:0,\r
615             c:null,\r
616             s:"(?:\\d{2})" // no. of days in the month (28 - 31)\r
617         },\r
618         L: {\r
619             g:0,\r
620             c:null,\r
621             s:"(?:1|0)"\r
622         },\r
623         o: function() {\r
624             return $f("Y");\r
625         },\r
626         Y: {\r
627             g:1,\r
628             c:"y = parseInt(results[{0}], 10);\n",\r
629             s:"(\\d{4})" // 4-digit year\r
630         },\r
631         y: {\r
632             g:1,\r
633             c:"var ty = parseInt(results[{0}], 10);\n"\r
634                 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year\r
635             s:"(\\d{1,2})"\r
636         },\r
637         a: {\r
638             g:1,\r
639             c:"if (results[{0}] == 'am') {\n"\r
640                 + "if (h == 12) { h = 0; }\n"\r
641                 + "} else { if (h < 12) { h += 12; }}",\r
642             s:"(am|pm)"\r
643         },\r
644         A: {\r
645             g:1,\r
646             c:"if (results[{0}] == 'AM') {\n"\r
647                 + "if (h == 12) { h = 0; }\n"\r
648                 + "} else { if (h < 12) { h += 12; }}",\r
649             s:"(AM|PM)"\r
650         },\r
651         g: function() {\r
652             return $f("G");\r
653         },\r
654         G: {\r
655             g:1,\r
656             c:"h = parseInt(results[{0}], 10);\n",\r
657             s:"(\\d{1,2})" // 24-hr format of an hour without leading zeroes (0 - 23)\r
658         },\r
659         h: function() {\r
660             return $f("H");\r
661         },\r
662         H: {\r
663             g:1,\r
664             c:"h = parseInt(results[{0}], 10);\n",\r
665             s:"(\\d{2})" //  24-hr format of an hour with leading zeroes (00 - 23)\r
666         },\r
667         i: {\r
668             g:1,\r
669             c:"i = parseInt(results[{0}], 10);\n",\r
670             s:"(\\d{2})" // minutes with leading zeros (00 - 59)\r
671         },\r
672         s: {\r
673             g:1,\r
674             c:"s = parseInt(results[{0}], 10);\n",\r
675             s:"(\\d{2})" // seconds with leading zeros (00 - 59)\r
676         },\r
677         u: {\r
678             g:1,\r
679             c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",\r
680             s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)\r
681         },\r
682         O: {\r
683             g:1,\r
684             c:[\r
685                 "o = results[{0}];",\r
686                 "var sn = o.substring(0,1);", // get + / - sign\r
687                 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);", // get hours (performs minutes-to-hour conversion also, just in case)\r
688                 "var mn = o.substring(3,5) % 60;", // get minutes\r
689                 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + String.leftPad(hr, 2, '0') + String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs\r
690             ].join("\n"),\r
691             s: "([+\-]\\d{4})" // GMT offset in hrs and mins\r
692         },\r
693         P: {\r
694             g:1,\r
695             c:[\r
696                 "o = results[{0}];",\r
697                 "var sn = o.substring(0,1);", // get + / - sign\r
698                 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);", // get hours (performs minutes-to-hour conversion also, just in case)\r
699                 "var mn = o.substring(4,6) % 60;", // get minutes\r
700                 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + String.leftPad(hr, 2, '0') + String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs\r
701             ].join("\n"),\r
702             s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)\r
703         },\r
704         T: {\r
705             g:0,\r
706             c:null,\r
707             s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars\r
708         },\r
709         Z: {\r
710             g:1,\r
711             c:"z = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400\r
712                   + "z = (-43200 <= z && z <= 50400)? z : null;\n",\r
713             s:"([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset\r
714         },\r
715         c: function() {\r
716             var calc = [],\r
717                 arr = [\r
718                     $f("Y", 1), // year\r
719                     $f("m", 2), // month\r
720                     $f("d", 3), // day\r
721                     $f("h", 4), // hour\r
722                     $f("i", 5), // minute\r
723                     $f("s", 6), // second\r
724                     {c:"ms = (results[7] || '.0').substring(1); ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n"}, // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)\r
725                     {c:[ // allow both "Z" (i.e. UTC) and "+08:00" (i.e. UTC offset) time zone delimiters\r
726                         "if(results[9] == 'Z'){",\r
727                             "z = 0;",\r
728                         "}else{",\r
729                             $f("P", 9).c,\r
730                         "}"\r
731                     ].join('\n')}\r
732                 ];\r
733 \r
734             for (var i = 0, l = arr.length; i < l; ++i) {\r
735                 calc.push(arr[i].c);\r
736             }\r
737 \r
738             return {\r
739                 g:1,\r
740                 c:calc.join(""),\r
741                 s:arr[0].s + "-" + arr[1].s + "-" + arr[2].s + "T" + arr[3].s + ":" + arr[4].s + ":" + arr[5].s\r
742                       + "((\.|,)\\d+)?" // decimal fraction of a second (e.g. ",998465" or ".998465")\r
743                       + "(Z|([+\-]\\d{2}:\\d{2}))" // "Z" (UTC) or "+08:00" (UTC offset)\r
744             }\r
745         },\r
746         U: {\r
747             g:1,\r
748             c:"u = parseInt(results[{0}], 10);\n",\r
749             s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch\r
750         }\r
751     }\r
752 });\r
753 \r
754 }());\r
755 \r
756 Ext.apply(Date.prototype, {\r
757     // private\r
758     dateFormat : function(format) {\r
759         if (Date.formatFunctions[format] == null) {\r
760             Date.createNewFormat(format);\r
761         }\r
762         var func = Date.formatFunctions[format];\r
763         return this[func]();\r
764     },\r
765 \r
766     /**\r
767      * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').\r
768      *\r
769      * Note: The date string returned by the javascript Date object's toString() method varies\r
770      * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).\r
771      * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",\r
772      * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses\r
773      * (which may or may not be present), failing which it proceeds to get the timezone abbreviation\r
774      * from the GMT offset portion of the date string.\r
775      * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).\r
776      */\r
777     getTimezone : function() {\r
778         // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:\r
779         //\r
780         // Opera  : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot\r
781         // 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)\r
782         // FF     : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone\r
783         // IE     : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev\r
784         // IE     : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev\r
785         //\r
786         // this crazy regex attempts to guess the correct timezone abbreviation despite these differences.\r
787         // step 1: (?:\((.*)\) -- find timezone in parentheses\r
788         // 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\r
789         // step 3: remove all non uppercase characters found in step 1 and 2\r
790         return this.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");\r
791     },\r
792 \r
793     /**\r
794      * Get the offset from GMT of the current date (equivalent to the format specifier 'O').\r
795      * @param {Boolean} colon true to separate the hours and minutes with a colon (defaults to false).\r
796      * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').\r
797      */\r
798     getGMTOffset : function(colon) {\r
799         return (this.getTimezoneOffset() > 0 ? "-" : "+")\r
800             + String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset()) / 60), 2, "0")\r
801             + (colon ? ":" : "")\r
802             + String.leftPad(Math.abs(this.getTimezoneOffset() % 60), 2, "0");\r
803     },\r
804 \r
805     /**\r
806      * Get the numeric day number of the year, adjusted for leap year.\r
807      * @return {Number} 0 to 364 (365 in leap years).\r
808      */\r
809     getDayOfYear : function() {\r
810         var num = 0;\r
811         Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;\r
812         for (var i = 0; i < this.getMonth(); ++i) {\r
813             num += Date.daysInMonth[i];\r
814         }\r
815         return num + this.getDate() - 1;\r
816     },\r
817 \r
818     /**\r
819      * Get the numeric ISO-8601 week number of the year.\r
820      * (equivalent to the format specifier 'W', but without a leading zero).\r
821      * @return {Number} 1 to 53\r
822      */\r
823     getWeekOfYear : function() {\r
824         // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm\r
825         var ms1d = 864e5, // milliseconds in a day\r
826             ms7d = 7 * ms1d; // milliseconds in a week\r
827 \r
828         return function() { // return a closure so constants get calculated only once\r
829             var DC3 = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate() + 3) / ms1d, // an Absolute Day Number\r
830                 AWN = Math.floor(DC3 / 7), // an Absolute Week Number\r
831                 Wyr = new Date(AWN * ms7d).getUTCFullYear();\r
832 \r
833             return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;\r
834         }\r
835     }(),\r
836 \r
837     /**\r
838      * Whether or not the current date is in a leap year.\r
839      * @return {Boolean} True if the current date is in a leap year, else false.\r
840      */\r
841     isLeapYear : function() {\r
842         var year = this.getFullYear();\r
843         return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));\r
844     },\r
845 \r
846     /**\r
847      * Get the first day of the current month, adjusted for leap year.  The returned value\r
848      * is the numeric day index within the week (0-6) which can be used in conjunction with\r
849      * the {@link #monthNames} array to retrieve the textual day name.\r
850      * Example:\r
851      *<pre><code>\r
852     var dt = new Date('1/10/2007');\r
853     document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'\r
854     </code></pre>\r
855      * @return {Number} The day number (0-6).\r
856      */\r
857     getFirstDayOfMonth : function() {\r
858         var day = (this.getDay() - (this.getDate() - 1)) % 7;\r
859         return (day < 0) ? (day + 7) : day;\r
860     },\r
861 \r
862     /**\r
863      * Get the last day of the current month, adjusted for leap year.  The returned value\r
864      * is the numeric day index within the week (0-6) which can be used in conjunction with\r
865      * the {@link #monthNames} array to retrieve the textual day name.\r
866      * Example:\r
867      *<pre><code>\r
868     var dt = new Date('1/10/2007');\r
869     document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'\r
870     </code></pre>\r
871      * @return {Number} The day number (0-6).\r
872      */\r
873     getLastDayOfMonth : function() {\r
874         var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;\r
875         return (day < 0) ? (day + 7) : day;\r
876     },\r
877 \r
878 \r
879     /**\r
880      * Get the date of the first day of the month in which this date resides.\r
881      * @return {Date}\r
882      */\r
883     getFirstDateOfMonth : function() {\r
884         return new Date(this.getFullYear(), this.getMonth(), 1);\r
885     },\r
886 \r
887     /**\r
888      * Get the date of the last day of the month in which this date resides.\r
889      * @return {Date}\r
890      */\r
891     getLastDateOfMonth : function() {\r
892         return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());\r
893     },\r
894 \r
895     /**\r
896      * Get the number of days in the current month, adjusted for leap year.\r
897      * @return {Number} The number of days in the month.\r
898      */\r
899     getDaysInMonth : function() {\r
900         Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;\r
901         return Date.daysInMonth[this.getMonth()];\r
902     },\r
903 \r
904     /**\r
905      * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').\r
906      * @return {String} 'st, 'nd', 'rd' or 'th'.\r
907      */\r
908     getSuffix : function() {\r
909         switch (this.getDate()) {\r
910             case 1:\r
911             case 21:\r
912             case 31:\r
913                 return "st";\r
914             case 2:\r
915             case 22:\r
916                 return "nd";\r
917             case 3:\r
918             case 23:\r
919                 return "rd";\r
920             default:\r
921                 return "th";\r
922         }\r
923     },\r
924 \r
925     /**\r
926      * Creates and returns a new Date instance with the exact same date value as the called instance.\r
927      * Dates are copied and passed by reference, so if a copied date variable is modified later, the original\r
928      * variable will also be changed.  When the intention is to create a new variable that will not\r
929      * modify the original instance, you should create a clone.\r
930      *\r
931      * Example of correctly cloning a date:\r
932      * <pre><code>\r
933     //wrong way:\r
934     var orig = new Date('10/1/2006');\r
935     var copy = orig;\r
936     copy.setDate(5);\r
937     document.write(orig);  //returns 'Thu Oct 05 2006'!\r
938 \r
939     //correct way:\r
940     var orig = new Date('10/1/2006');\r
941     var copy = orig.clone();\r
942     copy.setDate(5);\r
943     document.write(orig);  //returns 'Thu Oct 01 2006'\r
944     </code></pre>\r
945      * @return {Date} The new Date instance.\r
946      */\r
947     clone : function() {\r
948         return new Date(this.getTime());\r
949     },\r
950 \r
951     /**\r
952      * Clears any time information from this date.\r
953      @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).\r
954      @return {Date} this or the clone.\r
955      */\r
956     clearTime : function(clone){\r
957         if(clone){\r
958             return this.clone().clearTime();\r
959         }\r
960         this.setHours(0);\r
961         this.setMinutes(0);\r
962         this.setSeconds(0);\r
963         this.setMilliseconds(0);\r
964         return this;\r
965     },\r
966 \r
967     /**\r
968      * Provides a convenient method of performing basic date arithmetic.  This method\r
969      * does not modify the Date instance being called - it creates and returns\r
970      * a new Date instance containing the resulting date value.\r
971      *\r
972      * Examples:\r
973      * <pre><code>\r
974     //Basic usage:\r
975     var dt = new Date('10/29/2006').add(Date.DAY, 5);\r
976     document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'\r
977 \r
978     //Negative values will subtract correctly:\r
979     var dt2 = new Date('10/1/2006').add(Date.DAY, -5);\r
980     document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'\r
981 \r
982     //You can even chain several calls together in one line!\r
983     var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);\r
984     document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'\r
985      </code></pre>\r
986      *\r
987      * @param {String} interval   A valid date interval enum value.\r
988      * @param {Number} value      The amount to add to the current date.\r
989      * @return {Date} The new Date instance.\r
990      */\r
991     add : function(interval, value){\r
992         var d = this.clone();\r
993         if (!interval || value === 0) return d;\r
994 \r
995         switch(interval.toLowerCase()){\r
996             case Date.MILLI:\r
997                 d.setMilliseconds(this.getMilliseconds() + value);\r
998                 break;\r
999             case Date.SECOND:\r
1000                 d.setSeconds(this.getSeconds() + value);\r
1001                 break;\r
1002             case Date.MINUTE:\r
1003                 d.setMinutes(this.getMinutes() + value);\r
1004                 break;\r
1005             case Date.HOUR:\r
1006                 d.setHours(this.getHours() + value);\r
1007                 break;\r
1008             case Date.DAY:\r
1009                 d.setDate(this.getDate() + value);\r
1010                 break;\r
1011             case Date.MONTH:\r
1012                 var day = this.getDate();\r
1013                 if(day > 28){\r
1014                     day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());\r
1015                 }\r
1016                 d.setDate(day);\r
1017                 d.setMonth(this.getMonth() + value);\r
1018                 break;\r
1019             case Date.YEAR:\r
1020                 d.setFullYear(this.getFullYear() + value);\r
1021                 break;\r
1022         }\r
1023         return d;\r
1024     },\r
1025 \r
1026     /**\r
1027      * Checks if this date falls on or between the given start and end dates.\r
1028      * @param {Date} start Start date\r
1029      * @param {Date} end End date\r
1030      * @return {Boolean} true if this date falls on or between the given start and end dates.\r
1031      */\r
1032     between : function(start, end){\r
1033         var t = this.getTime();\r
1034         return start.getTime() <= t && t <= end.getTime();\r
1035     }\r
1036 });\r
1037 \r
1038 \r
1039 /**\r
1040  * Formats a date given the supplied format string.\r
1041  * @param {String} format The format string.\r
1042  * @return {String} The formatted date.\r
1043  * @method format\r
1044  */\r
1045 Date.prototype.format = Date.prototype.dateFormat;\r
1046 \r
1047 \r
1048 // private\r
1049 // safari setMonth is broken\r
1050 if(Ext.isSafari){\r
1051     Date.brokenSetMonth = Date.prototype.setMonth;\r
1052     Date.prototype.setMonth = function(num){\r
1053         if(num <= -1){\r
1054             var n = Math.ceil(-num);\r
1055             var back_year = Math.ceil(n/12);\r
1056             var month = (n % 12) ? 12 - n % 12 : 0 ;\r
1057             this.setFullYear(this.getFullYear() - back_year);\r
1058             return Date.brokenSetMonth.call(this, month);\r
1059         } else {\r
1060             return Date.brokenSetMonth.apply(this, arguments);\r
1061         }\r
1062     };\r
1063 }