Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / core / src / lang / Date.js
similarity index 66%
rename from src/util/Date.js
rename to src/core/src/lang/Date.js
index 44eaa3a..b59d193 100644 (file)
@@ -1,18 +1,15 @@
-/*!
- * Ext JS Library 3.3.1
- * Copyright(c) 2006-2010 Sencha Inc.
- * licensing@sencha.com
- * http://www.sencha.com/license
- */
 /**
- * @class Date
+ * @class Ext.Date
+ * A set of useful static methods to deal with date
+ * Note that if Ext.Date is required and loaded, it will copy all methods / properties to
+ * this object for convenience
  *
  * The date parsing and formatting syntax contains a subset of
  * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
  * supported will provide results equivalent to their PHP versions.
  *
  * The following is a list of all currently supported formats:
- * <pre>
+ * <pre class="">
 Format  Description                                                               Example returned values
 ------  -----------------------------------------------------------------------   -----------------------
   d     Day of the month, 2 digits with leading zeros                             01 to 31
@@ -29,7 +26,7 @@ Format  Description
   M     A short textual representation of a month                                 Jan to Dec
   n     Numeric representation of a month, without leading zeros                  1 to 12
   t     Number of days in the given month                                         28 to 31
-  L     Whether it's a leap year                                                  1 if it is a leap year, 0 otherwise.
+  L     Whether it&#39;s a leap year                                                  1 if it is a leap year, 0 otherwise.
   o     ISO-8601 year number (identical to (Y), but if the ISO week number (W)    Examples: 1998 or 2004
         belongs to the previous or next year, that year is used instead)
   Y     A full numeric representation of a year, 4 digits                         Examples: 1999 or 2003
@@ -65,7 +62,7 @@ Format  Description
         date-time granularity which are supported, or see                         2000-02-13T21:25:33
         http://www.w3.org/TR/NOTE-datetime for more info.                         2001-01-12 22:26:34
   U     Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)                1193432466 or -2138434463
-  M$    Microsoft AJAX serialized dates                                           \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
+  MS    Microsoft AJAX serialized dates                                           \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
                                                                                   \/Date(1238606590509+0800)\/
 </pre>
  *
@@ -75,17 +72,17 @@ Format  Description
 // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
 
 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
-document.write(dt.format('Y-m-d'));                           // 2007-01-10
-document.write(dt.format('F j, Y, g:i a'));                   // January 10, 2007, 3:05 pm
-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
+console.log(Ext.Date.format(dt, 'Y-m-d'));                          // 2007-01-10
+console.log(Ext.Date.format(dt, 'F j, Y, g:i a'));                  // January 10, 2007, 3:05 pm
+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
 </code></pre>
  *
  * Here are some standard date/time patterns that you might find helpful.  They
- * are not part of the source of Date.js, but to use them you can simply copy this
- * block of code into any script that is included after Date.js and they will also become
+ * are not part of the source of Ext.Date, but to use them you can simply copy this
+ * block of code into any script that is included after Ext.Date and they will also become
  * globally available on the Date object.  Feel free to add or remove patterns as needed in your code.
  * <pre><code>
-Date.patterns = {
+Ext.Date.patterns = {
     ISO8601Long:"Y-m-d H:i:s",
     ISO8601Short:"Y-m-d",
     ShortDate: "n/j/Y",
@@ -103,10 +100,11 @@ Date.patterns = {
  * Example usage:
  * <pre><code>
 var dt = new Date();
-document.write(dt.format(Date.patterns.ShortDate));
+console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
 </code></pre>
  * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
  * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
+ * @singleton
  */
 
 /*
@@ -119,21 +117,9 @@ document.write(dt.format(Date.patterns.ShortDate));
 
 (function() {
 
-/**
- * Global flag which determines if strict date parsing should be used.
- * Strict date parsing will not roll-over invalid dates, which is the
- * default behaviour of javascript Date objects.
- * (see {@link #parseDate} for more information)
- * Defaults to <tt>false</tt>.
- * @static
- * @type Boolean
-*/
-Date.useStrict = false;
-
-
-// create private copy of Ext's String.format() method
+// create private copy of Ext's Ext.util.Format.format() method
 // - to remove unnecessary dependency
-// - to resolve namespace conflict with M$-Ajax's implementation
+// - to resolve namespace conflict with MS-Ajax's implementation
 function xf(format) {
     var args = Array.prototype.slice.call(arguments, 1);
     return format.replace(/\{(\d+)\}/g, function(m, i) {
@@ -141,39 +127,79 @@ function xf(format) {
     });
 }
 
+Ext.Date = {
+    /**
+     * Returns the current timestamp
+     * @return {Date} The current timestamp
+     */
+    now: Date.now || function() {
+        return +new Date();
+    },
 
-// private
-Date.formatCodeToRegex = function(character, currentGroup) {
-    // Note: currentGroup - position in regex result array (see notes for Date.parseCodes below)
-    var p = Date.parseCodes[character];
+    /**
+     * @private
+     * Private for now
+     */
+    toString: function(date) {
+        var pad = Ext.String.leftPad;
+
+        return date.getFullYear() + "-"
+            + pad(date.getMonth() + 1, 2, '0') + "-"
+            + pad(date.getDate(), 2, '0') + "T"
+            + pad(date.getHours(), 2, '0') + ":"
+            + pad(date.getMinutes(), 2, '0') + ":"
+            + pad(date.getSeconds(), 2, '0');
+    },
 
-    if (p) {
-      p = typeof p == 'function'? p() : p;
-      Date.parseCodes[character] = p; // reassign function result to prevent repeated execution
-    }
+    /**
+     * Returns the number of milliseconds between two dates
+     * @param {Date} dateA The first date
+     * @param {Date} dateB (optional) The second date, defaults to now
+     * @return {Number} The difference in milliseconds
+     */
+    getElapsed: function(dateA, dateB) {
+        return Math.abs(dateA - (dateB || new Date()));
+    },
 
-    return p ? Ext.applyIf({
-      c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
-    }, p) : {
-        g:0,
-        c:null,
-        s:Ext.escapeRe(character) // treat unrecognised characters as literals
-    };
-};
+    /**
+     * Global flag which determines if strict date parsing should be used.
+     * Strict date parsing will not roll-over invalid dates, which is the
+     * default behaviour of javascript Date objects.
+     * (see {@link #parse} for more information)
+     * Defaults to <tt>false</tt>.
+     * @static
+     * @type Boolean
+    */
+    useStrict: false,
+
+    // private
+    formatCodeToRegex: function(character, currentGroup) {
+        // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below)
+        var p = utilDate.parseCodes[character];
+
+        if (p) {
+          p = typeof p == 'function'? p() : p;
+          utilDate.parseCodes[character] = p; // reassign function result to prevent repeated execution
+        }
 
-// private shorthand for Date.formatCodeToRegex since we'll be using it fairly often
-var $f = Date.formatCodeToRegex;
+        return p ? Ext.applyIf({
+          c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
+        }, p) : {
+            g: 0,
+            c: null,
+            s: Ext.String.escapeRegex(character) // treat unrecognised characters as literals
+        };
+    },
 
-Ext.apply(Date, {
     /**
      * <p>An object hash in which each property is a date parsing function. The property name is the
      * format string which that function parses.</p>
      * <p>This object is automatically populated with date parsing functions as
      * date formats are requested for Ext standard formatting strings.</p>
      * <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
-     * may be used as a format string to {@link #parseDate}.<p>
+     * may be used as a format string to {@link #parse}.<p>
      * <p>Example:</p><pre><code>
-Date.parseFunctions['x-date-format'] = myDateParser;
+Ext.Date.parseFunctions['x-date-format'] = myDateParser;
 </code></pre>
      * <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
      * <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
@@ -188,8 +214,8 @@ Date.parseFunctions['x-date-format'] = myDateParser;
      * @type Object
      */
     parseFunctions: {
-        "M$": function(input, strict) {
-            // note: the timezone offset is ignored since the M$ Ajax server sends
+        "MS": function(input, strict) {
+            // note: the timezone offset is ignored since the MS Ajax server sends
             // a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
             var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/');
             var r = (input || '').match(re);
@@ -205,7 +231,7 @@ Date.parseFunctions['x-date-format'] = myDateParser;
      * date formats are requested for Ext standard formatting strings.</p>
      * <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
      * may be used as a format string to {@link #format}. Example:</p><pre><code>
-Date.formatFunctions['x-date-format'] = myDateFormatter;
+Ext.Date.formatFunctions['x-date-format'] = myDateFormatter;
 </code></pre>
      * <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>
      * <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
@@ -217,8 +243,8 @@ Date.formatFunctions['x-date-format'] = myDateFormatter;
      * @type Object
      */
     formatFunctions: {
-        "M$": function() {
-            // UTC milliseconds since Unix epoch (M$-AJAX serialized date format (MRSF))
+        "MS": function() {
+            // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF))
             return '\\/Date(' + this.getTime() + ')\\/';
         }
     },
@@ -284,19 +310,19 @@ Date.formatFunctions['x-date-format'] = myDateFormatter;
      * <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
      * <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
      * </ul></div></p>
-     * <p>Override these properties to customize the default date values used by the {@link #parseDate} method.</p>
+     * <p>Override these properties to customize the default date values used by the {@link #parse} method.</p>
      * <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
      * and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
      * It is the responsiblity of the developer to account for this.</b></p>
      * Example Usage:
      * <pre><code>
 // set default day value to the first day of the month
-Date.defaults.d = 1;
+Ext.Date.defaults.d = 1;
 
 // parse a February date string containing only year and month values.
 // setting the default day value to 1 prevents weird date rollover issues
 // when attempting to parse the following date string on, for example, March 31st 2009.
-Date.parseDate('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
+Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
 </code></pre>
      * @property defaults
      * @static
@@ -309,7 +335,7 @@ Date.parseDate('2009-02', 'Y-m'); // returns a Date object representing February
      * Override these values for international dates.
      * Example:
      * <pre><code>
-Date.dayNames = [
+Ext.Date.dayNames = [
     'SundayInYourLang',
     'MondayInYourLang',
     ...
@@ -333,7 +359,7 @@ Date.dayNames = [
      * Override these values for international dates.
      * Example:
      * <pre><code>
-Date.monthNames = [
+Ext.Date.monthNames = [
     'JanInYourLang',
     'FebInYourLang',
     ...
@@ -362,7 +388,7 @@ Date.monthNames = [
      * Override these values for international dates.
      * Example:
      * <pre><code>
-Date.monthNumbers = {
+Ext.Date.monthNumbers = {
     'ShortJanNameInYourLang':0,
     'ShortFebNameInYourLang':1,
     ...
@@ -385,7 +411,15 @@ Date.monthNumbers = {
         Nov:10,
         Dec:11
     },
-
+    /**
+     * <p>The date format string that the {@link #dateRenderer} and {@link #date} functions use.
+     * see {@link #Date} for details.</p>
+     * <p>This defaults to <code>m/d/Y</code>, but may be overridden in a locale file.</p>
+     * @property defaultFormat
+     * @static
+     * @type String
+     */
+    defaultFormat : "m/d/Y",
     /**
      * Get the short month name for the given month number.
      * Override this function for international dates.
@@ -394,7 +428,7 @@ Date.monthNumbers = {
      * @static
      */
     getShortMonthName : function(month) {
-        return Date.monthNames[month].substring(0, 3);
+        return utilDate.monthNames[month].substring(0, 3);
     },
 
     /**
@@ -405,7 +439,7 @@ Date.monthNumbers = {
      * @static
      */
     getShortDayName : function(day) {
-        return Date.dayNames[day].substring(0, 3);
+        return utilDate.dayNames[day].substring(0, 3);
     },
 
     /**
@@ -416,62 +450,93 @@ Date.monthNumbers = {
      * @static
      */
     getMonthNumber : function(name) {
-        // handle camel casing for english month names (since the keys for the Date.monthNumbers hash are case sensitive)
-        return Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
+        // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive)
+        return utilDate.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
     },
 
+    /**
+     * Checks if the specified format contains hour information
+     * @param {String} format The format to check
+     * @return {Boolean} True if the format contains hour information
+     * @static
+     */
+    formatContainsHourInfo : (function(){
+        var stripEscapeRe = /(\\.)/g,
+            hourInfoRe = /([gGhHisucUOPZ]|MS)/;
+        return function(format){
+            return hourInfoRe.test(format.replace(stripEscapeRe, ''));
+        };
+    })(),
+
+    /**
+     * Checks if the specified format contains information about
+     * anything other than the time.
+     * @param {String} format The format to check
+     * @return {Boolean} True if the format contains information about
+     * date/day information.
+     * @static
+     */
+    formatContainsDateInfo : (function(){
+        var stripEscapeRe = /(\\.)/g,
+            dateInfoRe = /([djzmnYycU]|MS)/;
+
+        return function(format){
+            return dateInfoRe.test(format.replace(stripEscapeRe, ''));
+        };
+    })(),
+
     /**
      * The base format-code to formatting-function hashmap used by the {@link #format} method.
      * Formatting functions are strings (or functions which return strings) which
      * will return the appropriate value when evaluated in the context of the Date object
      * from which the {@link #format} method is called.
      * Add to / override these mappings for custom date formatting.
-     * Note: Date.format() treats characters as literals if an appropriate mapping cannot be found.
+     * Note: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found.
      * Example:
      * <pre><code>
-Date.formatCodes.x = "String.leftPad(this.getDate(), 2, '0')";
-(new Date()).format("X"); // returns the current day of the month
+Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
+console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
 </code></pre>
      * @type Object
      * @static
      */
     formatCodes : {
-        d: "String.leftPad(this.getDate(), 2, '0')",
-        D: "Date.getShortDayName(this.getDay())", // get localised short day name
+        d: "Ext.String.leftPad(this.getDate(), 2, '0')",
+        D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name
         j: "this.getDate()",
-        l: "Date.dayNames[this.getDay()]",
+        l: "Ext.Date.dayNames[this.getDay()]",
         N: "(this.getDay() ? this.getDay() : 7)",
-        S: "this.getSuffix()",
+        S: "Ext.Date.getSuffix(this)",
         w: "this.getDay()",
-        z: "this.getDayOfYear()",
-        W: "String.leftPad(this.getWeekOfYear(), 2, '0')",
-        F: "Date.monthNames[this.getMonth()]",
-        m: "String.leftPad(this.getMonth() + 1, 2, '0')",
-        M: "Date.getShortMonthName(this.getMonth())", // get localised short month name
+        z: "Ext.Date.getDayOfYear(this)",
+        W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')",
+        F: "Ext.Date.monthNames[this.getMonth()]",
+        m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')",
+        M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name
         n: "(this.getMonth() + 1)",
-        t: "this.getDaysInMonth()",
-        L: "(this.isLeapYear() ? 1 : 0)",
-        o: "(this.getFullYear() + (this.getWeekOfYear() == 1 && this.getMonth() > 0 ? +1 : (this.getWeekOfYear() >= 52 && this.getMonth() < 11 ? -1 : 0)))",
-        Y: "String.leftPad(this.getFullYear(), 4, '0')",
+        t: "Ext.Date.getDaysInMonth(this)",
+        L: "(Ext.Date.isLeapYear(this) ? 1 : 0)",
+        o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",
+        Y: "Ext.String.leftPad(this.getFullYear(), 4, '0')",
         y: "('' + this.getFullYear()).substring(2, 4)",
         a: "(this.getHours() < 12 ? 'am' : 'pm')",
         A: "(this.getHours() < 12 ? 'AM' : 'PM')",
         g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
         G: "this.getHours()",
-        h: "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
-        H: "String.leftPad(this.getHours(), 2, '0')",
-        i: "String.leftPad(this.getMinutes(), 2, '0')",
-        s: "String.leftPad(this.getSeconds(), 2, '0')",
-        u: "String.leftPad(this.getMilliseconds(), 3, '0')",
-        O: "this.getGMTOffset()",
-        P: "this.getGMTOffset(true)",
-        T: "this.getTimezone()",
+        h: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
+        H: "Ext.String.leftPad(this.getHours(), 2, '0')",
+        i: "Ext.String.leftPad(this.getMinutes(), 2, '0')",
+        s: "Ext.String.leftPad(this.getSeconds(), 2, '0')",
+        u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')",
+        O: "Ext.Date.getGMTOffset(this)",
+        P: "Ext.Date.getGMTOffset(this, true)",
+        T: "Ext.Date.getTimezone(this)",
         Z: "(this.getTimezoneOffset() * -60)",
 
         c: function() { // ISO-8601 -- GMT format
             for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
                 var e = c.charAt(i);
-                code.push(e == "T" ? "'T'" : Date.getFormatCode(e)); // treat T as a character literal
+                code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal
             }
             return code.join(" + ");
         },
@@ -479,12 +544,12 @@ Date.formatCodes.x = "String.leftPad(this.getDate(), 2, '0')";
         c: function() { // ISO-8601 -- UTC format
             return [
               "this.getUTCFullYear()", "'-'",
-              "String.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
-              "String.leftPad(this.getUTCDate(), 2, '0')",
+              "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
+              "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')",
               "'T'",
-              "String.leftPad(this.getUTCHours(), 2, '0')", "':'",
-              "String.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
-              "String.leftPad(this.getUTCSeconds(), 2, '0')",
+              "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'",
+              "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
+              "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')",
               "'Z'"
             ].join(" + ");
         },
@@ -513,7 +578,7 @@ Date.formatCodes.x = "String.leftPad(this.getDate(), 2, '0')";
         ms = ms || 0;
 
         // Special handling for year < 100
-        var dt = new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms).add(Date.YEAR, y < 100 ? y - 100 : 0);
+        var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.YEAR, y < 100 ? y - 100 : 0);
 
         return y == dt.getFullYear() &&
             m == dt.getMonth() + 1 &&
@@ -537,16 +602,16 @@ Date.formatCodes.x = "String.leftPad(this.getDate(), 2, '0')";
 var dt = new Date();
 
 //dt = Thu May 25 2006 (today&#39;s month/day in 2006)
-dt = Date.parseDate("2006", "Y");
+dt = Ext.Date.parse("2006", "Y");
 
 //dt = Sun Jan 15 2006 (all date parts specified)
-dt = Date.parseDate("2006-01-15", "Y-m-d");
+dt = Ext.Date.parse("2006-01-15", "Y-m-d");
 
 //dt = Sun Jan 15 2006 15:20:01
-dt = Date.parseDate("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
+dt = Ext.Date.parse("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
 
 // attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
-dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
+dt = Ext.Date.parse("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
 </code></pre>
      * @param {String} input The raw date string.
      * @param {String} format The expected date string format.
@@ -555,25 +620,31 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
      * @return {Date} The parsed Date.
      * @static
      */
-    parseDate : function(input, format, strict) {
-        var p = Date.parseFunctions;
+    parse : function(input, format, strict) {
+        var p = utilDate.parseFunctions;
         if (p[format] == null) {
-            Date.createParser(format);
+            utilDate.createParser(format);
         }
-        return p[format](input, Ext.isDefined(strict) ? strict : Date.useStrict);
+        return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict);
+    },
+
+    // Backwards compat
+    parseDate: function(input, format, strict){
+        return utilDate.parse(input, format, strict);
     },
 
+
     // private
     getFormatCode : function(character) {
-        var f = Date.formatCodes[character];
+        var f = utilDate.formatCodes[character];
 
         if (f) {
           f = typeof f == 'function'? f() : f;
-          Date.formatCodes[character] = f; // reassign function result to prevent repeated execution
+          utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution
         }
 
         // note: unknown characters are treated as literals
-        return f || ("'" + String.escape(character) + "'");
+        return f || ("'" + Ext.String.escape(character) + "'");
     },
 
     // private
@@ -588,20 +659,20 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
                 special = true;
             } else if (special) {
                 special = false;
-                code.push("'" + String.escape(ch) + "'");
+                code.push("'" + Ext.String.escape(ch) + "'");
             } else {
-                code.push(Date.getFormatCode(ch));
+                code.push(utilDate.getFormatCode(ch));
             }
         }
-        Date.formatFunctions[format] = new Function("return " + code.join('+'));
+        utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+'));
     },
 
     // private
-    createParser : function() {
+    createParser : (function() {
         var code = [
             "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
-                "def = Date.defaults,",
-                "results = String(input).match(Date.parseRegexes[{0}]);", // either null, or an array of matched strings
+                "def = Ext.Date.defaults,",
+                "results = String(input).match(Ext.Date.parseRegexes[{0}]);", // either null, or an array of matched strings
 
             "if(results){",
                 "{1}",
@@ -612,18 +683,18 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
                     // create Date object representing midnight of the current day;
                     // this will provide us with our date defaults
                     // (note: clearTime() handles Daylight Saving Time automatically)
-                    "dt = (new Date()).clearTime();",
+                    "dt = Ext.Date.clearTime(new Date);",
 
-                    // date calculations (note: these calculations create a dependency on Ext.num())
-                    "y = Ext.num(y, Ext.num(def.y, dt.getFullYear()));",
-                    "m = Ext.num(m, Ext.num(def.m - 1, dt.getMonth()));",
-                    "d = Ext.num(d, Ext.num(def.d, dt.getDate()));",
+                    // date calculations (note: these calculations create a dependency on Ext.Number.from())
+                    "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));",
+                    "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));",
+                    "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));",
 
-                    // time calculations (note: these calculations create a dependency on Ext.num())
-                    "h  = Ext.num(h, Ext.num(def.h, dt.getHours()));",
-                    "i  = Ext.num(i, Ext.num(def.i, dt.getMinutes()));",
-                    "s  = Ext.num(s, Ext.num(def.s, dt.getSeconds()));",
-                    "ms = Ext.num(ms, Ext.num(def.ms, dt.getMilliseconds()));",
+                    // time calculations (note: these calculations create a dependency on Ext.Number.from())
+                    "h  = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));",
+                    "i  = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));",
+                    "s  = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));",
+                    "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));",
 
                     "if(z >= 0 && y >= 0){",
                         // both the year and zero-based day of year are defined and >= 0.
@@ -631,16 +702,16 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
 
                         // create Date object representing January 1st for the given year
                         // handle years < 100 appropriately
-                        "v = new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms).add(Date.YEAR, y < 100 ? y - 100 : 0);",
+                        "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
 
                         // then add day of year, checking for Date "rollover" if necessary
-                        "v = !strict? v : (strict === true && (z <= 364 || (v.isLeapYear() && z <= 365))? v.add(Date.DAY, z) : null);",
-                    "}else if(strict === true && !Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
+                        "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);",
+                    "}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
                         "v = null;", // invalid date, so return null
                     "}else{",
                         // plain old Date object
                         // handle years < 100 properly
-                        "v = new Date(y < 100 ? 100 : y, m, d, h, i, s, ms).add(Date.YEAR, y < 100 ? y - 100 : 0);",
+                        "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
                     "}",
                 "}",
             "}",
@@ -649,10 +720,10 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
                 // favour UTC offset over GMT offset
                 "if(zz != null){",
                     // reset to UTC, then add offset
-                    "v = v.add(Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
+                    "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
                 "}else if(o){",
                     // reset to GMT, then add offset
-                    "v = v.add(Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
+                    "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
                 "}",
             "}",
 
@@ -660,45 +731,34 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
         ].join('\n');
 
         return function(format) {
-            var regexNum = Date.parseRegexes.length,
+            var regexNum = utilDate.parseRegexes.length,
                 currentGroup = 1,
                 calc = [],
                 regex = [],
                 special = false,
-                ch = "",
-                i = 0,
-                obj,
-                last;
+                ch = "";
 
-            for (; i < format.length; ++i) {
+            for (var i = 0; i < format.length; ++i) {
                 ch = format.charAt(i);
                 if (!special && ch == "\\") {
                     special = true;
                 } else if (special) {
                     special = false;
-                    regex.push(String.escape(ch));
+                    regex.push(Ext.String.escape(ch));
                 } else {
-                    obj = $f(ch, currentGroup);
+                    var obj = utilDate.formatCodeToRegex(ch, currentGroup);
                     currentGroup += obj.g;
                     regex.push(obj.s);
                     if (obj.g && obj.c) {
-                        if (obj.calcLast) {
-                            last = obj.c;
-                        } else {
-                            calc.push(obj.c);
-                        }
+                        calc.push(obj.c);
                     }
                 }
             }
-            
-            if (last) {
-                calc.push(last);
-            }
 
-            Date.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
-            Date.parseFunctions[format] = new Function("input", "strict", xf(code, regexNum, calc.join('')));
+            utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
+            utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join('')));
         };
-    }(),
+    })(),
 
     // private
     parseCodes : {
@@ -719,7 +779,7 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
             s:"(\\d{1,2})" // day of month without leading zeroes (1 - 31)
         },
         D: function() {
-            for (var a = [], i = 0; i < 7; a.push(Date.getShortDayName(i)), ++i); // get localised short day names
+            for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names
             return {
                 g:0,
                 c:null,
@@ -730,7 +790,7 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
             return {
                 g:0,
                 c:null,
-                s:"(?:" + Date.dayNames.join("|") + ")"
+                s:"(?:" + utilDate.dayNames.join("|") + ")"
             };
         },
         N: {
@@ -761,15 +821,15 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
         F: function() {
             return {
                 g:1,
-                c:"m = parseInt(Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
-                s:"(" + Date.monthNames.join("|") + ")"
+                c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
+                s:"(" + utilDate.monthNames.join("|") + ")"
             };
         },
         M: function() {
-            for (var a = [], i = 0; i < 12; a.push(Date.getShortMonthName(i)), ++i); // get localised short month names
+            for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names
             return Ext.applyIf({
                 s:"(" + a.join("|") + ")"
-            }, $f("F"));
+            }, utilDate.formatCodeToRegex("F"));
         },
         m: {
             g:1,
@@ -792,7 +852,7 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
             s:"(?:1|0)"
         },
         o: function() {
-            return $f("Y");
+            return utilDate.formatCodeToRegex("Y");
         },
         Y: {
             g:1,
@@ -802,20 +862,22 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
         y: {
             g:1,
             c:"var ty = parseInt(results[{0}], 10);\n"
-                + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
+                + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
             s:"(\\d{1,2})"
         },
         /**
-         * In the am/pm parsing routines, we allow both upper and lower case 
+         * In the am/pm parsing routines, we allow both upper and lower case
          * even though it doesn't exactly match the spec. It gives much more flexibility
          * in being able to specify case insensitive regexes.
          */
-        a: function(){
-            return $f("A");
+        a: {
+            g:1,
+            c:"if (/(am)/i.test(results[{0}])) {\n"
+                + "if (!h || h == 12) { h = 0; }\n"
+                + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
+            s:"(am|pm|AM|PM)"
         },
         A: {
-            // We need to calculate the hour before we apply AM/PM when parsing
-            calcLast: true,
             g:1,
             c:"if (/(am)/i.test(results[{0}])) {\n"
                 + "if (!h || h == 12) { h = 0; }\n"
@@ -823,7 +885,7 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
             s:"(AM|PM|am|pm)"
         },
         g: function() {
-            return $f("G");
+            return utilDate.formatCodeToRegex("G");
         },
         G: {
             g:1,
@@ -831,7 +893,7 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
             s:"(\\d{1,2})" // 24-hr format of an hour without leading zeroes (0 - 23)
         },
         h: function() {
-            return $f("H");
+            return utilDate.formatCodeToRegex("H");
         },
         H: {
             g:1,
@@ -860,7 +922,7 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
                 "var sn = o.substring(0,1),", // get + / - sign
                     "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
                     "mn = o.substring(3,5) % 60;", // get minutes
-                "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
+                "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
             ].join("\n"),
             s: "([+\-]\\d{4})" // GMT offset in hrs and mins
         },
@@ -871,7 +933,7 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
                 "var sn = o.substring(0,1),", // get + / - sign
                     "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
                     "mn = o.substring(4,6) % 60;", // get minutes
-                "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
+                "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
             ].join("\n"),
             s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
         },
@@ -889,21 +951,21 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
         c: function() {
             var calc = [],
                 arr = [
-                    $f("Y", 1), // year
-                    $f("m", 2), // month
-                    $f("d", 3), // day
-                    $f("h", 4), // hour
-                    $f("i", 5), // minute
-                    $f("s", 6), // second
+                    utilDate.formatCodeToRegex("Y", 1), // year
+                    utilDate.formatCodeToRegex("m", 2), // month
+                    utilDate.formatCodeToRegex("d", 3), // day
+                    utilDate.formatCodeToRegex("h", 4), // hour
+                    utilDate.formatCodeToRegex("i", 5), // minute
+                    utilDate.formatCodeToRegex("s", 6), // second
                     {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)
                     {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
                         "if(results[8]) {", // timezone specified
                             "if(results[8] == 'Z'){",
                                 "zz = 0;", // UTC
                             "}else if (results[8].indexOf(':') > -1){",
-                                $f("P", 8).c, // timezone offset with colon separator
+                                utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator
                             "}else{",
-                                $f("O", 8).c, // timezone offset without colon separator
+                                utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator
                             "}",
                         "}"
                     ].join('\n')}
@@ -937,18 +999,26 @@ dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
             c:"u = parseInt(results[{0}], 10);\n",
             s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
         }
-    }
-});
-
-}());
+    },
 
-Ext.apply(Date.prototype, {
+    //Old Ext.Date prototype methods.
     // private
-    dateFormat : function(format) {
-        if (Date.formatFunctions[format] == null) {
-            Date.createFormat(format);
+    dateFormat: function(date, format) {
+        return utilDate.format(date, format);
+    },
+
+    /**
+     * Formats a date given the supplied format string.
+     * @param {Date} date The date to format
+     * @param {String} format The format string
+     * @return {String} The formatted date
+     */
+    format: function(date, format) {
+        if (utilDate.formatFunctions[format] == null) {
+            utilDate.createFormat(format);
         }
-        return Date.formatFunctions[format].call(this);
+        var result = utilDate.formatFunctions[format].call(date);
+        return result + '';
     },
 
     /**
@@ -960,9 +1030,10 @@ Ext.apply(Date.prototype, {
      * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
      * (which may or may not be present), failing which it proceeds to get the timezone abbreviation
      * from the GMT offset portion of the date string.
+     * @param {Date} date The date
      * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
      */
-    getTimezone : function() {
+    getTimezone : function(date) {
         // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
         //
         // Opera  : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
@@ -975,62 +1046,67 @@ Ext.apply(Date.prototype, {
         // step 1: (?:\((.*)\) -- find timezone in parentheses
         // 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
         // step 3: remove all non uppercase characters found in step 1 and 2
-        return this.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
+        return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
     },
 
     /**
      * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
+     * @param {Date} date The date
      * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
      * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
      */
-    getGMTOffset : function(colon) {
-        return (this.getTimezoneOffset() > 0 ? "-" : "+")
-            + String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset()) / 60), 2, "0")
+    getGMTOffset : function(date, colon) {
+        var offset = date.getTimezoneOffset();
+        return (offset > 0 ? "-" : "+")
+            + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0")
             + (colon ? ":" : "")
-            + String.leftPad(Math.abs(this.getTimezoneOffset() % 60), 2, "0");
+            + Ext.String.leftPad(Math.abs(offset % 60), 2, "0");
     },
 
     /**
      * Get the numeric day number of the year, adjusted for leap year.
+     * @param {Date} date The date
      * @return {Number} 0 to 364 (365 in leap years).
      */
-    getDayOfYear: function() {
+    getDayOfYear: function(date) {
         var num = 0,
-            d = this.clone(),
-            m = this.getMonth(),
+            d = Ext.Date.clone(date),
+            m = date.getMonth(),
             i;
 
         for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
-            num += d.getDaysInMonth();
+            num += utilDate.getDaysInMonth(d);
         }
-        return num + this.getDate() - 1;
+        return num + date.getDate() - 1;
     },
 
     /**
      * Get the numeric ISO-8601 week number of the year.
      * (equivalent to the format specifier 'W', but without a leading zero).
+     * @param {Date} date The date
      * @return {Number} 1 to 53
      */
-    getWeekOfYear : function() {
+    getWeekOfYear : (function() {
         // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
         var ms1d = 864e5, // milliseconds in a day
             ms7d = 7 * ms1d; // milliseconds in a week
 
-        return function() { // return a closure so constants get calculated only once
-            var DC3 = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate() + 3) / ms1d, // an Absolute Day Number
+        return function(date) { // return a closure so constants get calculated only once
+            var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number
                 AWN = Math.floor(DC3 / 7), // an Absolute Week Number
                 Wyr = new Date(AWN * ms7d).getUTCFullYear();
 
             return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
         };
-    }(),
+    })(),
 
     /**
      * Checks if the current date falls within a leap year.
+     * @param {Date} date The date
      * @return {Boolean} True if the current date falls within a leap year, false otherwise.
      */
-    isLeapYear : function() {
-        var year = this.getFullYear();
+    isLeapYear : function(date) {
+        var year = date.getFullYear();
         return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
     },
 
@@ -1040,13 +1116,15 @@ Ext.apply(Date.prototype, {
      * the {@link #monthNames} array to retrieve the textual day name.
      * Example:
      * <pre><code>
-var dt = new Date('1/10/2007');
-document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
-</code></pre>
+var dt = new Date('1/10/2007'),
+    firstDay = Ext.Date.getFirstDayOfMonth(dt);
+console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
+     * </code></pre>
+     * @param {Date} date The date
      * @return {Number} The day number (0-6).
      */
-    getFirstDayOfMonth : function() {
-        var day = (this.getDay() - (this.getDate() - 1)) % 7;
+    getFirstDayOfMonth : function(date) {
+        var day = (date.getDay() - (date.getDate() - 1)) % 7;
         return (day < 0) ? (day + 7) : day;
     },
 
@@ -1056,52 +1134,58 @@ document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
      * the {@link #monthNames} array to retrieve the textual day name.
      * Example:
      * <pre><code>
-var dt = new Date('1/10/2007');
-document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
-</code></pre>
+var dt = new Date('1/10/2007'),
+    lastDay = Ext.Date.getLastDayOfMonth(dt);
+console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
+     * </code></pre>
+     * @param {Date} date The date
      * @return {Number} The day number (0-6).
      */
-    getLastDayOfMonth : function() {
-        return this.getLastDateOfMonth().getDay();
+    getLastDayOfMonth : function(date) {
+        return utilDate.getLastDateOfMonth(date).getDay();
     },
 
 
     /**
      * Get the date of the first day of the month in which this date resides.
+     * @param {Date} date The date
      * @return {Date}
      */
-    getFirstDateOfMonth : function() {
-        return new Date(this.getFullYear(), this.getMonth(), 1);
+    getFirstDateOfMonth : function(date) {
+        return new Date(date.getFullYear(), date.getMonth(), 1);
     },
 
     /**
      * Get the date of the last day of the month in which this date resides.
+     * @param {Date} date The date
      * @return {Date}
      */
-    getLastDateOfMonth : function() {
-        return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
+    getLastDateOfMonth : function(date) {
+        return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date));
     },
 
     /**
      * Get the number of days in the current month, adjusted for leap year.
+     * @param {Date} date The date
      * @return {Number} The number of days in the month.
      */
-    getDaysInMonth: function() {
+    getDaysInMonth: (function() {
         var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
 
-        return function() { // return a closure for efficiency
-            var m = this.getMonth();
+        return function(date) { // return a closure for efficiency
+            var m = date.getMonth();
 
-            return m == 1 && this.isLeapYear() ? 29 : daysInMonth[m];
+            return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m];
         };
-    }(),
+    })(),
 
     /**
      * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
+     * @param {Date} date The date
      * @return {String} 'st, 'nd', 'rd' or 'th'.
      */
-    getSuffix : function() {
-        switch (this.getDate()) {
+    getSuffix : function(date) {
+        switch (date.getDate()) {
             case 1:
             case 21:
             case 31:
@@ -1129,63 +1213,66 @@ document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
 var orig = new Date('10/1/2006');
 var copy = orig;
 copy.setDate(5);
-document.write(orig);  //returns 'Thu Oct 05 2006'!
+console.log(orig);  //returns 'Thu Oct 05 2006'!
 
 //correct way:
-var orig = new Date('10/1/2006');
-var copy = orig.clone();
+var orig = new Date('10/1/2006'),
+    copy = Ext.Date.clone(orig);
 copy.setDate(5);
-document.write(orig);  //returns 'Thu Oct 01 2006'
-</code></pre>
+console.log(orig);  //returns 'Thu Oct 01 2006'
+     * </code></pre>
+     * @param {Date} date The date
      * @return {Date} The new Date instance.
      */
-    clone : function() {
-        return new Date(this.getTime());
+    clone : function(date) {
+        return new Date(date.getTime());
     },
 
     /**
      * Checks if the current date is affected by Daylight Saving Time (DST).
+     * @param {Date} date The date
      * @return {Boolean} True if the current date is affected by DST.
      */
-    isDST : function() {
-        // adapted from http://extjs.com/forum/showthread.php?p=247172#post247172
+    isDST : function(date) {
+        // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172
         // courtesy of @geoffrey.mcgill
-        return new Date(this.getFullYear(), 0, 1).getTimezoneOffset() != this.getTimezoneOffset();
+        return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset();
     },
 
     /**
      * Attempts to clear all time information from this Date by setting the time to midnight of the same day,
      * automatically adjusting for Daylight Saving Time (DST) where applicable.
      * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
+     * @param {Date} date The date
      * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
      * @return {Date} this or the clone.
      */
-    clearTime : function(clone) {
+    clearTime : function(date, clone) {
         if (clone) {
-            return this.clone().clearTime();
+            return Ext.Date.clearTime(Ext.Date.clone(date));
         }
 
         // get current date before clearing time
-        var d = this.getDate();
+        var d = date.getDate();
 
         // clear time
-        this.setHours(0);
-        this.setMinutes(0);
-        this.setSeconds(0);
-        this.setMilliseconds(0);
+        date.setHours(0);
+        date.setMinutes(0);
+        date.setSeconds(0);
+        date.setMilliseconds(0);
 
-        if (this.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
+        if (date.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
             // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
             // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
 
             // increment hour until cloned date == current date
-            for (var hr = 1, c = this.add(Date.HOUR, hr); c.getDate() != d; hr++, c = this.add(Date.HOUR, hr));
+            for (var hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr));
 
-            this.setDate(d);
-            this.setHours(c.getHours());
+            date.setDate(d);
+            date.setHours(c.getHours());
         }
 
-        return this;
+        return date;
     },
 
     /**
@@ -1196,139 +1283,91 @@ document.write(orig);  //returns 'Thu Oct 01 2006'
      * Examples:
      * <pre><code>
 // Basic usage:
-var dt = new Date('10/29/2006').add(Date.DAY, 5);
-document.write(dt); //returns 'Fri Nov 03 2006 00:00:00'
+var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
+console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
 
 // Negative values will be subtracted:
-var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
-document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
+var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
+console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
 
-// You can even chain several calls together in one line:
-var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
-document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
-</code></pre>
+     * </code></pre>
      *
+     * @param {Date} date The date to modify
      * @param {String} interval A valid date interval enum value.
      * @param {Number} value The amount to add to the current date.
      * @return {Date} The new Date instance.
      */
-    add : function(interval, value) {
-        var d = this.clone();
+    add : function(date, interval, value) {
+        var d = Ext.Date.clone(date),
+            Date = Ext.Date;
         if (!interval || value === 0) return d;
 
         switch(interval.toLowerCase()) {
-            case Date.MILLI:
-                d.setMilliseconds(this.getMilliseconds() + value);
+            case Ext.Date.MILLI:
+                d.setMilliseconds(d.getMilliseconds() + value);
                 break;
-            case Date.SECOND:
-                d.setSeconds(this.getSeconds() + value);
+            case Ext.Date.SECOND:
+                d.setSeconds(d.getSeconds() + value);
                 break;
-            case Date.MINUTE:
-                d.setMinutes(this.getMinutes() + value);
+            case Ext.Date.MINUTE:
+                d.setMinutes(d.getMinutes() + value);
                 break;
-            case Date.HOUR:
-                d.setHours(this.getHours() + value);
+            case Ext.Date.HOUR:
+                d.setHours(d.getHours() + value);
                 break;
-            case Date.DAY:
-                d.setDate(this.getDate() + value);
+            case Ext.Date.DAY:
+                d.setDate(d.getDate() + value);
                 break;
-            case Date.MONTH:
-                var day = this.getDate();
+            case Ext.Date.MONTH:
+                var day = date.getDate();
                 if (day > 28) {
-                    day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
+                    day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), 'mo', value)).getDate());
                 }
                 d.setDate(day);
-                d.setMonth(this.getMonth() + value);
+                d.setMonth(date.getMonth() + value);
                 break;
-            case Date.YEAR:
-                d.setFullYear(this.getFullYear() + value);
+            case Ext.Date.YEAR:
+                d.setFullYear(date.getFullYear() + value);
                 break;
         }
         return d;
     },
 
     /**
-     * Checks if this date falls on or between the given start and end dates.
+     * Checks if a date falls on or between the given start and end dates.
+     * @param {Date} date The date to check
      * @param {Date} start Start date
      * @param {Date} end End date
      * @return {Boolean} true if this date falls on or between the given start and end dates.
      */
-    between : function(start, end) {
-        var t = this.getTime();
+    between : function(date, start, end) {
+        var t = date.getTime();
         return start.getTime() <= t && t <= end.getTime();
-    }
-});
-
-
-/**
- * Formats a date given the supplied format string.
- * @param {String} format The format string.
- * @return {String} The formatted date.
- * @method format
- */
-Date.prototype.format = Date.prototype.dateFormat;
-
-
-// private
-if (Ext.isSafari && (navigator.userAgent.match(/WebKit\/(\d+)/)[1] || NaN) < 420) {
-    Ext.apply(Date.prototype, {
-        _xMonth : Date.prototype.setMonth,
-        _xDate  : Date.prototype.setDate,
-
-        // Bug in Safari 1.3, 2.0 (WebKit build < 420)
-        // Date.setMonth does not work consistently if iMonth is not 0-11
-        setMonth : function(num) {
-            if (num <= -1) {
-                var n = Math.ceil(-num),
-                    back_year = Math.ceil(n / 12),
-                    month = (n % 12) ? 12 - n % 12 : 0;
-
-                this.setFullYear(this.getFullYear() - back_year);
-
-                return this._xMonth(month);
-            } else {
-                return this._xMonth(num);
-            }
-        },
-
-        // Bug in setDate() method (resolved in WebKit build 419.3, so to be safe we target Webkit builds < 420)
-        // The parameter for Date.setDate() is converted to a signed byte integer in Safari
-        // http://brianary.blogspot.com/2006/03/safari-date-bug.html
-        setDate : function(d) {
-            // use setTime() to workaround setDate() bug
-            // subtract current day of month in milliseconds, then add desired day of month in milliseconds
-            return this.setTime(this.getTime() - (this.getDate() - d) * 864e5);
-        }
-    });
-}
-
-
-
-/* Some basic Date tests... (requires Firebug)
-
-Date.parseDate('', 'c'); // call Date.parseDate() once to force computation of regex string so we can console.log() it
-console.log('Insane Regex for "c" format: %o', Date.parseCodes.c.s); // view the insane regex for the "c" format specifier
+    },
 
-// standard tests
-console.group('Standard Date.parseDate() Tests');
-    console.log('Date.parseDate("2009-01-05T11:38:56", "c")               = %o', Date.parseDate("2009-01-05T11:38:56", "c")); // assumes browser's timezone setting
-    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
-    console.log('Date.parseDate("2009-03-03T13:36:54,101000Z", "c")       = %o', Date.parseDate("2009-03-03T13:36:54,101000Z", "c")); // UTC
-    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
-    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
-console.groupEnd();
+    //Maintains compatibility with old static and prototype window.Date methods.
+    compat: function() {
+        var nativeDate = window.Date,
+            p, u,
+            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'],
+            proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'];
+
+        //Append statics
+        Ext.Array.forEach(statics, function(s) {
+            nativeDate[s] = utilDate[s];
+        });
+
+        //Append to prototype
+        Ext.Array.forEach(proto, function(s) {
+            nativeDate.prototype[s] = function() {
+                var args = Array.prototype.slice.call(arguments);
+                args.unshift(this);
+                return utilDate[s].apply(utilDate, args);
+            };
+        });
+    }
+};
 
-// ISO-8601 format as specified in http://www.w3.org/TR/NOTE-datetime
-// -- accepts ALL 6 levels of date-time granularity
-console.group('ISO-8601 Granularity Test (see http://www.w3.org/TR/NOTE-datetime)');
-    console.log('Date.parseDate("1997", "c")                              = %o', Date.parseDate("1997", "c")); // YYYY (e.g. 1997)
-    console.log('Date.parseDate("1997-07", "c")                           = %o', Date.parseDate("1997-07", "c")); // YYYY-MM (e.g. 1997-07)
-    console.log('Date.parseDate("1997-07-16", "c")                        = %o', Date.parseDate("1997-07-16", "c")); // YYYY-MM-DD (e.g. 1997-07-16)
-    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)
-    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)
-    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)
-    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)
-    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
-console.groupEnd();
+var utilDate = Ext.Date;
 
-*/
+})();