3 <title>The source code</title>
4 <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
5 <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
7 <body onload="prettyPrint();">
8 <pre class="prettyprint lang-js">/*!
10 * Copyright(c) 2006-2009 Ext JS, LLC
12 * http://www.extjs.com/license
14 <div id="cls-Date"></div>/**
17 * The date parsing and formatting syntax contains a subset of
18 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
19 * supported will provide results equivalent to their PHP versions.
21 * The following is a list of all currently supported formats:
23 Format Description Example returned values
24 ------ ----------------------------------------------------------------------- -----------------------
25 d Day of the month, 2 digits with leading zeros 01 to 31
26 D A short textual representation of the day of the week Mon to Sun
27 j Day of the month without leading zeros 1 to 31
28 l A full textual representation of the day of the week Sunday to Saturday
29 N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
30 S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
31 w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
32 z The day of the year (starting from 0) 0 to 364 (365 in leap years)
33 W ISO-8601 week number of year, weeks starting on Monday 01 to 53
34 F A full textual representation of a month, such as January or March January to December
35 m Numeric representation of a month, with leading zeros 01 to 12
36 M A short textual representation of a month Jan to Dec
37 n Numeric representation of a month, without leading zeros 1 to 12
38 t Number of days in the given month 28 to 31
39 L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
40 o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
41 belongs to the previous or next year, that year is used instead)
42 Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
43 y A two digit representation of a year Examples: 99 or 03
44 a Lowercase Ante meridiem and Post meridiem am or pm
45 A Uppercase Ante meridiem and Post meridiem AM or PM
46 g 12-hour format of an hour without leading zeros 1 to 12
47 G 24-hour format of an hour without leading zeros 0 to 23
48 h 12-hour format of an hour with leading zeros 01 to 12
49 H 24-hour format of an hour with leading zeros 00 to 23
50 i Minutes, with leading zeros 00 to 59
51 s Seconds, with leading zeros 00 to 59
52 u Decimal fraction of a second Examples:
53 (minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
56 999876543210 (i.e. 0.999876543210s)
57 O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
58 P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
59 T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
60 Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
63 1) If unspecified, the month / day defaults to the current month / day, 1991 or
64 the time defaults to midnight, while the timezone defaults to the 1992-10 or
65 browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
66 and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
67 are optional. 1995-07-18T17:21:28-02:00 or
68 2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
69 least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
70 of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
71 Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
72 date-time granularity which are supported, or see 2000-02-13T21:25:33
73 http://www.w3.org/TR/NOTE-datetime for more info. 2001-01-12 22:26:34
74 U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
75 M$ Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
76 \/Date(1238606590509+0800)\/
79 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
82 // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
84 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
85 document.write(dt.format('Y-m-d')); // 2007-01-10
86 document.write(dt.format('F j, Y, g:i a')); // January 10, 2007, 3:05 pm
87 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
90 * Here are some standard date/time patterns that you might find helpful. They
91 * are not part of the source of Date.js, but to use them you can simply copy this
92 * block of code into any script that is included after Date.js and they will also become
93 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
96 ISO8601Long:"Y-m-d H:i:s",
99 LongDate: "l, F d, Y",
100 FullDateTime: "l, F d, Y g:i:s A",
104 SortableDateTime: "Y-m-d\\TH:i:s",
105 UniversalSortableDateTime: "Y-m-d H:i:sO",
113 document.write(dt.format(Date.patterns.ShortDate));
115 * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
116 * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
120 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
121 * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
122 * They generate precompiled functions from format patterns instead of parsing and
123 * processing each pattern every time a date is formatted. These functions are available
124 * on every Date object.
129 <div id="prop-Date-useStrict"></div>/**
130 * Global flag which determines if strict date parsing should be used.
131 * Strict date parsing will not roll-over invalid dates, which is the
132 * default behaviour of javascript Date objects.
133 * (see {@link #parseDate} for more information)
134 * Defaults to <tt>false</tt>.
138 Date.useStrict = false;
141 // create private copy of Ext's String.format() method
142 // - to remove unnecessary dependency
143 // - to resolve namespace conflict with M$-Ajax's implementation
144 function xf(format) {
145 var args = Array.prototype.slice.call(arguments, 1);
146 return format.replace(/\{(\d+)\}/g, function(m, i) {
153 Date.formatCodeToRegex = function(character, currentGroup) {
154 // Note: currentGroup - position in regex result array (see notes for Date.parseCodes below)
155 var p = Date.parseCodes[character];
158 p = typeof p == 'function'? p() : p;
159 Date.parseCodes[character] = p; // reassign function result to prevent repeated execution
162 return p? Ext.applyIf({
163 c: p.c? xf(p.c, currentGroup || "{0}") : p.c
167 s:Ext.escapeRe(character) // treat unrecognised characters as literals
171 // private shorthand for Date.formatCodeToRegex since we'll be using it fairly often
172 var $f = Date.formatCodeToRegex;
175 <div id="prop-Date-parseFunctions"></div>/**
176 * <p>An object hash in which each property is a date parsing function. The property name is the
177 * format string which that function parses.</p>
178 * <p>This object is automatically populated with date parsing functions as
179 * date formats are requested for Ext standard formatting strings.</p>
180 * <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
181 * may be used as a format string to {@link #parseDate}.<p>
182 * <p>Example:</p><pre><code>
183 Date.parseFunctions['x-date-format'] = myDateParser;
185 * <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
186 * <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
187 * <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
188 * (i.e. prevent javascript Date "rollover") (The default must be false).
189 * Invalid date strings should return null when parsed.</div></li>
191 * <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding
192 * formatting function must be placed into the {@link #formatFunctions} property.
193 * @property parseFunctions
198 "M$": function(input, strict) {
199 // note: the timezone offset is ignored since the M$ Ajax server sends
200 // a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
201 var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/');
202 var r = (input || '').match(re);
203 return r? new Date(((r[1] || '') + r[2]) * 1) : null;
208 <div id="prop-Date-formatFunctions"></div>/**
209 * <p>An object hash in which each property is a date formatting function. The property name is the
210 * format string which corresponds to the produced formatted date string.</p>
211 * <p>This object is automatically populated with date formatting functions as
212 * date formats are requested for Ext standard formatting strings.</p>
213 * <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
214 * may be used as a format string to {@link #format}. Example:</p><pre><code>
215 Date.formatFunctions['x-date-format'] = myDateFormatter;
217 * <p>A formatting function should return a string repesentation of the passed Date object:<div class="mdetail-params"><ul>
218 * <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
220 * <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding
221 * parsing function must be placed into the {@link #parseFunctions} property.
222 * @property formatFunctions
228 // UTC milliseconds since Unix epoch (M$-AJAX serialized date format (MRSF))
229 return '\\/Date(' + this.getTime() + ')\\/';
235 <div id="prop-Date-MILLI"></div>/**
236 * Date interval constant
242 <div id="prop-Date-SECOND"></div>/**
243 * Date interval constant
249 <div id="prop-Date-MINUTE"></div>/**
250 * Date interval constant
256 <div id="prop-Date-HOUR"></div>/** Date interval constant
262 <div id="prop-Date-DAY"></div>/**
263 * Date interval constant
269 <div id="prop-Date-MONTH"></div>/**
270 * Date interval constant
276 <div id="prop-Date-YEAR"></div>/**
277 * Date interval constant
283 <div id="prop-Date-defaults"></div>/**
284 * <p>An object hash containing default date values used during date parsing.</p>
285 * <p>The following properties are available:<div class="mdetail-params"><ul>
286 * <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
287 * <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
288 * <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
289 * <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
290 * <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
291 * <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
292 * <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
294 * <p>Override these properties to customize the default date values used by the {@link #parseDate} method.</p>
295 * <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
296 * and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
297 * It is the responsiblity of the developer to account for this.</b></p>
300 // set default day value to the first day of the month
303 // parse a February date string containing only year and month values.
304 // setting the default day value to 1 prevents weird date rollover issues
305 // when attempting to parse the following date string on, for example, March 31st 2009.
306 Date.parseDate('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
314 <div id="prop-Date-dayNames"></div>/**
315 * An array of textual day names.
316 * Override these values for international dates.
338 <div id="prop-Date-monthNames"></div>/**
339 * An array of textual month names.
340 * Override these values for international dates.
367 <div id="prop-Date-monthNumbers"></div>/**
368 * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
369 * Override these values for international dates.
372 Date.monthNumbers = {
373 'ShortJanNameInYourLang':0,
374 'ShortFebNameInYourLang':1,
396 <div id="method-Date-getShortMonthName"></div>/**
397 * Get the short month name for the given month number.
398 * Override this function for international dates.
399 * @param {Number} month A zero-based javascript month number.
400 * @return {String} The short month name.
403 getShortMonthName : function(month) {
404 return Date.monthNames[month].substring(0, 3);
407 <div id="method-Date-getShortDayName"></div>/**
408 * Get the short day name for the given day number.
409 * Override this function for international dates.
410 * @param {Number} day A zero-based javascript day number.
411 * @return {String} The short day name.
414 getShortDayName : function(day) {
415 return Date.dayNames[day].substring(0, 3);
418 <div id="method-Date-getMonthNumber"></div>/**
419 * Get the zero-based javascript month number for the given short/full month name.
420 * Override this function for international dates.
421 * @param {String} name The short/full month name.
422 * @return {Number} The zero-based javascript month number.
425 getMonthNumber : function(name) {
426 // handle camel casing for english month names (since the keys for the Date.monthNumbers hash are case sensitive)
427 return Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
430 <div id="prop-Date-formatCodes"></div>/**
431 * The base format-code to formatting-function hashmap used by the {@link #format} method.
432 * Formatting functions are strings (or functions which return strings) which
433 * will return the appropriate value when evaluated in the context of the Date object
434 * from which the {@link #format} method is called.
435 * Add to / override these mappings for custom date formatting.
436 * Note: Date.format() treats characters as literals if an appropriate mapping cannot be found.
439 Date.formatCodes.x = "String.leftPad(this.getDate(), 2, '0')";
440 (new Date()).format("X"); // returns the current day of the month
446 d: "String.leftPad(this.getDate(), 2, '0')",
447 D: "Date.getShortDayName(this.getDay())", // get localised short day name
449 l: "Date.dayNames[this.getDay()]",
450 N: "(this.getDay() ? this.getDay() : 7)",
451 S: "this.getSuffix()",
453 z: "this.getDayOfYear()",
454 W: "String.leftPad(this.getWeekOfYear(), 2, '0')",
455 F: "Date.monthNames[this.getMonth()]",
456 m: "String.leftPad(this.getMonth() + 1, 2, '0')",
457 M: "Date.getShortMonthName(this.getMonth())", // get localised short month name
458 n: "(this.getMonth() + 1)",
459 t: "this.getDaysInMonth()",
460 L: "(this.isLeapYear() ? 1 : 0)",
461 o: "(this.getFullYear() + (this.getWeekOfYear() == 1 && this.getMonth() > 0 ? +1 : (this.getWeekOfYear() >= 52 && this.getMonth() < 11 ? -1 : 0)))",
462 Y: "this.getFullYear()",
463 y: "('' + this.getFullYear()).substring(2, 4)",
464 a: "(this.getHours() < 12 ? 'am' : 'pm')",
465 A: "(this.getHours() < 12 ? 'AM' : 'PM')",
466 g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
467 G: "this.getHours()",
468 h: "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
469 H: "String.leftPad(this.getHours(), 2, '0')",
470 i: "String.leftPad(this.getMinutes(), 2, '0')",
471 s: "String.leftPad(this.getSeconds(), 2, '0')",
472 u: "String.leftPad(this.getMilliseconds(), 3, '0')",
473 O: "this.getGMTOffset()",
474 P: "this.getGMTOffset(true)",
475 T: "this.getTimezone()",
476 Z: "(this.getTimezoneOffset() * -60)",
478 c: function() { // ISO-8601 -- GMT format
479 for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
481 code.push(e == "T" ? "'T'" : Date.getFormatCode(e)); // treat T as a character literal
483 return code.join(" + ");
486 c: function() { // ISO-8601 -- UTC format
488 "this.getUTCFullYear()", "'-'",
489 "String.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
490 "String.leftPad(this.getUTCDate(), 2, '0')",
492 "String.leftPad(this.getUTCHours(), 2, '0')", "':'",
493 "String.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
494 "String.leftPad(this.getUTCSeconds(), 2, '0')",
500 U: "Math.round(this.getTime() / 1000)"
503 <div id="method-Date-isValid"></div>/**
504 * Checks if the passed Date parameters will cause a javascript Date "rollover".
505 * @param {Number} year 4-digit year
506 * @param {Number} month 1-based month-of-year
507 * @param {Number} day Day of month
508 * @param {Number} hour (optional) Hour
509 * @param {Number} minute (optional) Minute
510 * @param {Number} second (optional) Second
511 * @param {Number} millisecond (optional) Millisecond
512 * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
515 isValid : function(y, m, d, h, i, s, ms) {
522 var dt = new Date(y, m - 1, d, h, i, s, ms);
524 return y == dt.getFullYear() &&
525 m == dt.getMonth() + 1 &&
527 h == dt.getHours() &&
528 i == dt.getMinutes() &&
529 s == dt.getSeconds() &&
530 ms == dt.getMilliseconds();
533 <div id="method-Date-parseDate"></div>/**
534 * Parses the passed string using the specified date format.
535 * Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
536 * The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
537 * which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
538 * the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
539 * Keep in mind that the input date string must precisely match the specified format string
540 * in order for the parse operation to be successful (failed parse operations return a null value).
541 * <p>Example:</p><pre><code>
542 //dt = Fri May 25 2007 (current date)
545 //dt = Thu May 25 2006 (today's month/day in 2006)
546 dt = Date.parseDate("2006", "Y");
548 //dt = Sun Jan 15 2006 (all date parts specified)
549 dt = Date.parseDate("2006-01-15", "Y-m-d");
551 //dt = Sun Jan 15 2006 15:20:01
552 dt = Date.parseDate("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
554 // attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
555 dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
557 * @param {String} input The raw date string.
558 * @param {String} format The expected date string format.
559 * @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
560 (defaults to false). Invalid date strings will return null when parsed.
561 * @return {Date} The parsed Date.
564 parseDate : function(input, format, strict) {
565 var p = Date.parseFunctions;
566 if (p[format] == null) {
567 Date.createParser(format);
569 return p[format](input, Ext.isDefined(strict) ? strict : Date.useStrict);
573 getFormatCode : function(character) {
574 var f = Date.formatCodes[character];
577 f = typeof f == 'function'? f() : f;
578 Date.formatCodes[character] = f; // reassign function result to prevent repeated execution
581 // note: unknown characters are treated as literals
582 return f || ("'" + String.escape(character) + "'");
586 createFormat : function(format) {
591 for (var i = 0; i < format.length; ++i) {
592 ch = format.charAt(i);
593 if (!special && ch == "\\") {
595 } else if (special) {
597 code.push("'" + String.escape(ch) + "'");
599 code.push(Date.getFormatCode(ch))
602 Date.formatFunctions[format] = new Function("return " + code.join('+'));
606 createParser : function() {
608 "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
609 "def = Date.defaults,",
610 "results = String(input).match(Date.parseRegexes[{0}]);", // either null, or an array of matched strings
615 "if(u != null){", // i.e. unix time is defined
616 "v = new Date(u * 1000);", // give top priority to UNIX time
618 // create Date object representing midnight of the current day;
619 // this will provide us with our date defaults
620 // (note: clearTime() handles Daylight Saving Time automatically)
621 "dt = (new Date()).clearTime();",
623 // date calculations (note: these calculations create a dependency on Ext.num())
624 "y = y >= 0? y : Ext.num(def.y, dt.getFullYear());",
625 "m = m >= 0? m : Ext.num(def.m - 1, dt.getMonth());",
626 "d = d >= 0? d : Ext.num(def.d, dt.getDate());",
628 // time calculations (note: these calculations create a dependency on Ext.num())
629 "h = h || Ext.num(def.h, dt.getHours());",
630 "i = i || Ext.num(def.i, dt.getMinutes());",
631 "s = s || Ext.num(def.s, dt.getSeconds());",
632 "ms = ms || Ext.num(def.ms, dt.getMilliseconds());",
634 "if(z >= 0 && y >= 0){",
635 // both the year and zero-based day of year are defined and >= 0.
636 // these 2 values alone provide sufficient info to create a full date object
638 // create Date object representing January 1st for the given year
639 "v = new Date(y, 0, 1, h, i, s, ms);",
641 // then add day of year, checking for Date "rollover" if necessary
642 "v = !strict? v : (strict === true && (z <= 364 || (v.isLeapYear() && z <= 365))? v.add(Date.DAY, z) : null);",
643 "}else if(strict === true && !Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
644 "v = null;", // invalid date, so return null
646 // plain old Date object
647 "v = new Date(y, m, d, h, i, s, ms);",
653 // favour UTC offset over GMT offset
655 // reset to UTC, then add offset
656 "v = v.add(Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
658 // reset to GMT, then add offset
659 "v = v.add(Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
666 return function(format) {
667 var regexNum = Date.parseRegexes.length,
674 for (var i = 0; i < format.length; ++i) {
675 ch = format.charAt(i);
676 if (!special && ch == "\\") {
678 } else if (special) {
680 regex.push(String.escape(ch));
682 var obj = $f(ch, currentGroup);
683 currentGroup += obj.g;
685 if (obj.g && obj.c) {
691 Date.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", "i");
692 Date.parseFunctions[format] = new Function("input", "strict", xf(code, regexNum, calc.join('')));
700 * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
701 * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
702 * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
706 c:"d = parseInt(results[{0}], 10);\n",
707 s:"(\\d{2})" // day of month with leading zeroes (01 - 31)
711 c:"d = parseInt(results[{0}], 10);\n",
712 s:"(\\d{1,2})" // day of month without leading zeroes (1 - 31)
715 for (var a = [], i = 0; i < 7; a.push(Date.getShortDayName(i)), ++i); // get localised short day names
719 s:"(?:" + a.join("|") +")"
726 s:"(?:" + Date.dayNames.join("|") + ")"
732 s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
742 s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
746 c:"z = parseInt(results[{0}], 10);\n",
747 s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
752 s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)
757 c:"m = parseInt(Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
758 s:"(" + Date.monthNames.join("|") + ")"
762 for (var a = [], i = 0; i < 12; a.push(Date.getShortMonthName(i)), ++i); // get localised short month names
764 s:"(" + a.join("|") + ")"
769 c:"m = parseInt(results[{0}], 10) - 1;\n",
770 s:"(\\d{2})" // month number with leading zeros (01 - 12)
774 c:"m = parseInt(results[{0}], 10) - 1;\n",
775 s:"(\\d{1,2})" // month number without leading zeros (1 - 12)
780 s:"(?:\\d{2})" // no. of days in the month (28 - 31)
792 c:"y = parseInt(results[{0}], 10);\n",
793 s:"(\\d{4})" // 4-digit year
797 c:"var ty = parseInt(results[{0}], 10);\n"
798 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
803 c:"if (results[{0}] == 'am') {\n"
804 + "if (!h || h == 12) { h = 0; }\n"
805 + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
810 c:"if (results[{0}] == 'AM') {\n"
811 + "if (!h || h == 12) { h = 0; }\n"
812 + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
820 c:"h = parseInt(results[{0}], 10);\n",
821 s:"(\\d{1,2})" // 24-hr format of an hour without leading zeroes (0 - 23)
828 c:"h = parseInt(results[{0}], 10);\n",
829 s:"(\\d{2})" // 24-hr format of an hour with leading zeroes (00 - 23)
833 c:"i = parseInt(results[{0}], 10);\n",
834 s:"(\\d{2})" // minutes with leading zeros (00 - 59)
838 c:"s = parseInt(results[{0}], 10);\n",
839 s:"(\\d{2})" // seconds with leading zeros (00 - 59)
843 c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
844 s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
850 "var sn = o.substring(0,1),", // get + / - sign
851 "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
852 "mn = o.substring(3,5) % 60;", // get minutes
853 "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
855 s: "([+\-]\\d{4})" // GMT offset in hrs and mins
861 "var sn = o.substring(0,1),", // get + / - sign
862 "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
863 "mn = o.substring(4,6) % 60;", // get minutes
864 "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
866 s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
871 s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
875 c:"zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
876 + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
877 s:"([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
886 $f("i", 5), // minute
887 $f("s", 6), // second
888 {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)
889 {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
890 "if(results[8]) {", // timezone specified
891 "if(results[8] == 'Z'){",
893 "}else if (results[8].indexOf(':') > -1){",
894 $f("P", 8).c, // timezone offset with colon separator
896 $f("O", 8).c, // timezone offset without colon separator
902 for (var i = 0, l = arr.length; i < l; ++i) {
910 arr[0].s, // year (required)
911 "(?:", "-", arr[1].s, // month (optional)
912 "(?:", "-", arr[2].s, // day (optional)
914 "(?:T| )?", // time delimiter -- either a "T" or a single blank space
915 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
916 "(?::", arr[5].s, ")?", // seconds (optional)
917 "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
918 "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
927 c:"u = parseInt(results[{0}], 10);\n",
928 s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
935 Ext.apply(Date.prototype, {
937 dateFormat : function(format) {
938 if (Date.formatFunctions[format] == null) {
939 Date.createFormat(format);
941 return Date.formatFunctions[format].call(this);
944 <div id="method-Date-getTimezone"></div>/**
945 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
947 * Note: The date string returned by the javascript Date object's toString() method varies
948 * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
949 * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
950 * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
951 * (which may or may not be present), failing which it proceeds to get the timezone abbreviation
952 * from the GMT offset portion of the date string.
953 * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
955 getTimezone : function() {
956 // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
958 // Opera : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
959 // 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)
960 // FF : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
961 // IE : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
962 // IE : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
964 // this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
965 // step 1: (?:\((.*)\) -- find timezone in parentheses
966 // 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
967 // step 3: remove all non uppercase characters found in step 1 and 2
968 return this.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
971 <div id="method-Date-getGMTOffset"></div>/**
972 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
973 * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
974 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
976 getGMTOffset : function(colon) {
977 return (this.getTimezoneOffset() > 0 ? "-" : "+")
978 + String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset()) / 60), 2, "0")
980 + String.leftPad(Math.abs(this.getTimezoneOffset() % 60), 2, "0");
983 <div id="method-Date-getDayOfYear"></div>/**
984 * Get the numeric day number of the year, adjusted for leap year.
985 * @return {Number} 0 to 364 (365 in leap years).
987 getDayOfYear: function() {
993 for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
994 num += d.getDaysInMonth();
996 return num + this.getDate() - 1;
999 <div id="method-Date-getWeekOfYear"></div>/**
1000 * Get the numeric ISO-8601 week number of the year.
1001 * (equivalent to the format specifier 'W', but without a leading zero).
1002 * @return {Number} 1 to 53
1004 getWeekOfYear : function() {
1005 // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
1006 var ms1d = 864e5, // milliseconds in a day
1007 ms7d = 7 * ms1d; // milliseconds in a week
1009 return function() { // return a closure so constants get calculated only once
1010 var DC3 = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate() + 3) / ms1d, // an Absolute Day Number
1011 AWN = Math.floor(DC3 / 7), // an Absolute Week Number
1012 Wyr = new Date(AWN * ms7d).getUTCFullYear();
1014 return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
1018 <div id="method-Date-isLeapYear"></div>/**
1019 * Checks if the current date falls within a leap year.
1020 * @return {Boolean} True if the current date falls within a leap year, false otherwise.
1022 isLeapYear : function() {
1023 var year = this.getFullYear();
1024 return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1027 <div id="method-Date-getFirstDayOfMonth"></div>/**
1028 * Get the first day of the current month, adjusted for leap year. The returned value
1029 * is the numeric day index within the week (0-6) which can be used in conjunction with
1030 * the {@link #monthNames} array to retrieve the textual day name.
1033 var dt = new Date('1/10/2007');
1034 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1036 * @return {Number} The day number (0-6).
1038 getFirstDayOfMonth : function() {
1039 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1040 return (day < 0) ? (day + 7) : day;
1043 <div id="method-Date-getLastDayOfMonth"></div>/**
1044 * Get the last day of the current month, adjusted for leap year. The returned value
1045 * is the numeric day index within the week (0-6) which can be used in conjunction with
1046 * the {@link #monthNames} array to retrieve the textual day name.
1049 var dt = new Date('1/10/2007');
1050 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1052 * @return {Number} The day number (0-6).
1054 getLastDayOfMonth : function() {
1055 return this.getLastDateOfMonth().getDay();
1059 <div id="method-Date-getFirstDateOfMonth"></div>/**
1060 * Get the date of the first day of the month in which this date resides.
1063 getFirstDateOfMonth : function() {
1064 return new Date(this.getFullYear(), this.getMonth(), 1);
1067 <div id="method-Date-getLastDateOfMonth"></div>/**
1068 * Get the date of the last day of the month in which this date resides.
1071 getLastDateOfMonth : function() {
1072 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1075 <div id="method-Date-getDaysInMonth"></div>/**
1076 * Get the number of days in the current month, adjusted for leap year.
1077 * @return {Number} The number of days in the month.
1079 getDaysInMonth: function() {
1080 var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
1082 return function() { // return a closure for efficiency
1083 var m = this.getMonth();
1085 return m == 1 && this.isLeapYear() ? 29 : daysInMonth[m];
1089 <div id="method-Date-getSuffix"></div>/**
1090 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1091 * @return {String} 'st, 'nd', 'rd' or 'th'.
1093 getSuffix : function() {
1094 switch (this.getDate()) {
1110 <div id="method-Date-clone"></div>/**
1111 * Creates and returns a new Date instance with the exact same date value as the called instance.
1112 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1113 * variable will also be changed. When the intention is to create a new variable that will not
1114 * modify the original instance, you should create a clone.
1116 * Example of correctly cloning a date:
1119 var orig = new Date('10/1/2006');
1122 document.write(orig); //returns 'Thu Oct 05 2006'!
1125 var orig = new Date('10/1/2006');
1126 var copy = orig.clone();
1128 document.write(orig); //returns 'Thu Oct 01 2006'
1130 * @return {Date} The new Date instance.
1132 clone : function() {
1133 return new Date(this.getTime());
1136 <div id="method-Date-isDST"></div>/**
1137 * Checks if the current date is affected by Daylight Saving Time (DST).
1138 * @return {Boolean} True if the current date is affected by DST.
1140 isDST : function() {
1141 // adapted from http://extjs.com/forum/showthread.php?p=247172#post247172
1142 // courtesy of @geoffrey.mcgill
1143 return new Date(this.getFullYear(), 0, 1).getTimezoneOffset() != this.getTimezoneOffset();
1146 <div id="method-Date-clearTime"></div>/**
1147 * Attempts to clear all time information from this Date by setting the time to midnight of the same day,
1148 * automatically adjusting for Daylight Saving Time (DST) where applicable.
1149 * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
1150 * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
1151 * @return {Date} this or the clone.
1153 clearTime : function(clone) {
1155 return this.clone().clearTime();
1158 // get current date before clearing time
1159 var d = this.getDate();
1165 this.setMilliseconds(0);
1167 if (this.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
1168 // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
1169 // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
1171 // increment hour until cloned date == current date
1172 for (var hr = 1, c = this.add(Date.HOUR, hr); c.getDate() != d; hr++, c = this.add(Date.HOUR, hr));
1175 this.setHours(c.getHours());
1181 <div id="method-Date-add"></div>/**
1182 * Provides a convenient method for performing basic date arithmetic. This method
1183 * does not modify the Date instance being called - it creates and returns
1184 * a new Date instance containing the resulting date value.
1189 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1190 document.write(dt); //returns 'Fri Nov 03 2006 00:00:00'
1192 // Negative values will be subtracted:
1193 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1194 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1196 // You can even chain several calls together in one line:
1197 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1198 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1201 * @param {String} interval A valid date interval enum value.
1202 * @param {Number} value The amount to add to the current date.
1203 * @return {Date} The new Date instance.
1205 add : function(interval, value) {
1206 var d = this.clone();
1207 if (!interval || value === 0) return d;
1209 switch(interval.toLowerCase()) {
1211 d.setMilliseconds(this.getMilliseconds() + value);
1214 d.setSeconds(this.getSeconds() + value);
1217 d.setMinutes(this.getMinutes() + value);
1220 d.setHours(this.getHours() + value);
1223 d.setDate(this.getDate() + value);
1226 var day = this.getDate();
1228 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1231 d.setMonth(this.getMonth() + value);
1234 d.setFullYear(this.getFullYear() + value);
1240 <div id="method-Date-between"></div>/**
1241 * Checks if this date falls on or between the given start and end dates.
1242 * @param {Date} start Start date
1243 * @param {Date} end End date
1244 * @return {Boolean} true if this date falls on or between the given start and end dates.
1246 between : function(start, end) {
1247 var t = this.getTime();
1248 return start.getTime() <= t && t <= end.getTime();
1253 <div id="method-Date-format"></div>/**
1254 * Formats a date given the supplied format string.
1255 * @param {String} format The format string.
1256 * @return {String} The formatted date.
1259 Date.prototype.format = Date.prototype.dateFormat;
1263 if (Ext.isSafari && (navigator.userAgent.match(/WebKit\/(\d+)/)[1] || NaN) < 420) {
1264 Ext.apply(Date.prototype, {
1265 _xMonth : Date.prototype.setMonth,
1266 _xDate : Date.prototype.setDate,
1268 // Bug in Safari 1.3, 2.0 (WebKit build < 420)
1269 // Date.setMonth does not work consistently if iMonth is not 0-11
1270 setMonth : function(num) {
1272 var n = Math.ceil(-num),
1273 back_year = Math.ceil(n / 12),
1274 month = (n % 12) ? 12 - n % 12 : 0;
1276 this.setFullYear(this.getFullYear() - back_year);
1278 return this._xMonth(month);
1280 return this._xMonth(num);
1284 // Bug in setDate() method (resolved in WebKit build 419.3, so to be safe we target Webkit builds < 420)
1285 // The parameter for Date.setDate() is converted to a signed byte integer in Safari
1286 // http://brianary.blogspot.com/2006/03/safari-date-bug.html
1287 setDate : function(d) {
1288 // use setTime() to workaround setDate() bug
1289 // subtract current day of month in milliseconds, then add desired day of month in milliseconds
1290 return this.setTime(this.getTime() - (this.getDate() - d) * 864e5);
1297 /* Some basic Date tests... (requires Firebug)
1299 Date.parseDate('', 'c'); // call Date.parseDate() once to force computation of regex string so we can console.log() it
1300 console.log('Insane Regex for "c" format: %o', Date.parseCodes.c.s); // view the insane regex for the "c" format specifier
1303 console.group('Standard Date.parseDate() Tests');
1304 console.log('Date.parseDate("2009-01-05T11:38:56", "c") = %o', Date.parseDate("2009-01-05T11:38:56", "c")); // assumes browser's timezone setting
1305 console.log('Date.parseDate("2009-02-04T12:37:55.001000", "c") = %o', Date.parseDate("2009-02-04T12:37:55.001000", "c")); // assumes browser's timezone setting
1306 console.log('Date.parseDate("2009-03-03T13:36:54,101000Z", "c") = %o', Date.parseDate("2009-03-03T13:36:54,101000Z", "c")); // UTC
1307 console.log('Date.parseDate("2009-04-02T14:35:53.901000-0530", "c") = %o', Date.parseDate("2009-04-02T14:35:53.901000-0530", "c")); // GMT-0530
1308 console.log('Date.parseDate("2009-05-01T15:34:52,9876000+08:00", "c") = %o', Date.parseDate("2009-05-01T15:34:52,987600+08:00", "c")); // GMT+08:00
1311 // ISO-8601 format as specified in http://www.w3.org/TR/NOTE-datetime
1312 // -- accepts ALL 6 levels of date-time granularity
1313 console.group('ISO-8601 Granularity Test (see http://www.w3.org/TR/NOTE-datetime)');
1314 console.log('Date.parseDate("1997", "c") = %o', Date.parseDate("1997", "c")); // YYYY (e.g. 1997)
1315 console.log('Date.parseDate("1997-07", "c") = %o', Date.parseDate("1997-07", "c")); // YYYY-MM (e.g. 1997-07)
1316 console.log('Date.parseDate("1997-07-16", "c") = %o', Date.parseDate("1997-07-16", "c")); // YYYY-MM-DD (e.g. 1997-07-16)
1317 console.log('Date.parseDate("1997-07-16T19:20+01:00", "c") = %o', Date.parseDate("1997-07-16T19:20+01:00", "c")); // YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00)
1318 console.log('Date.parseDate("1997-07-16T19:20:30+01:00", "c") = %o', Date.parseDate("1997-07-16T19:20:30+01:00", "c")); // YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00)
1319 console.log('Date.parseDate("1997-07-16T19:20:30.45+01:00", "c") = %o', Date.parseDate("1997-07-16T19:20:30.45+01:00", "c")); // YYYY-MM-DDThh:mm:ss.sTZD (e.g. 1997-07-16T19:20:30.45+01:00)
1320 console.log('Date.parseDate("1997-07-16 19:20:30.45+01:00", "c") = %o', Date.parseDate("1997-07-16 19:20:30.45+01:00", "c")); // YYYY-MM-DD hh:mm:ss.sTZD (e.g. 1997-07-16T19:20:30.45+01:00)
1321 console.log('Date.parseDate("1997-13-16T19:20:30.45+01:00", "c", true)= %o', Date.parseDate("1997-13-16T19:20:30.45+01:00", "c", true)); // strict date parsing with invalid month value