DateExtra.js
[gnome.introspection-doc-generator] / DateExtra.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11 // usage: Date=  imports.Date.Date;
12
13
14 String          = imports.String.String;
15 XObject         = imports.XObject.XObject;
16
17
18 /**
19  * @class Date
20  *
21  * The date parsing and format syntax is a subset of
22  * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
23  * supported will provide results equivalent to their PHP versions.
24  *
25  * Following is the list of all currently supported formats:
26  *<pre>
27 Sample date:
28 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
29
30 Format  Output      Description
31 ------  ----------  --------------------------------------------------------------
32   d      10         Day of the month, 2 digits with leading zeros
33   D      Wed        A textual representation of a day, three letters
34   j      10         Day of the month without leading zeros
35   l      Wednesday  A full textual representation of the day of the week
36   S      th         English ordinal day of month suffix, 2 chars (use with j)
37   w      3          Numeric representation of the day of the week
38   z      9          The julian date, or day of the year (0-365)
39   W      01         ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
40   F      January    A full textual representation of the month
41   m      01         Numeric representation of a month, with leading zeros
42   M      Jan        Month name abbreviation, three letters
43   n      1          Numeric representation of a month, without leading zeros
44   t      31         Number of days in the given month
45   L      0          Whether it's a leap year (1 if it is a leap year, else 0)
46   Y      2007       A full numeric representation of a year, 4 digits
47   y      07         A two digit representation of a year
48   a      pm         Lowercase Ante meridiem and Post meridiem
49   A      PM         Uppercase Ante meridiem and Post meridiem
50   g      3          12-hour format of an hour without leading zeros
51   G      15         24-hour format of an hour without leading zeros
52   h      03         12-hour format of an hour with leading zeros
53   H      15         24-hour format of an hour with leading zeros
54   i      05         Minutes with leading zeros
55   s      01         Seconds, with leading zeros
56   O      -0600      Difference to Greenwich time (GMT) in hours
57   T      CST        Timezone setting of the machine running the code
58   Z      -21600     Timezone offset in seconds (negative if west of UTC, positive if east)
59 </pre>
60  *
61  * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
62  * <pre><code>
63 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
64 document.write(dt.format('Y-m-d'));                         //2007-01-10
65 document.write(dt.format('F j, Y, g:i a'));                 //January 10, 2007, 3:05 pm
66 document.write(dt.format('l, \\t\\he dS of F Y h:i:s A'));  //Wednesday, the 10th of January 2007 03:05:01 PM
67  </code></pre>
68  *
69  * Here are some standard date/time patterns that you might find helpful.  They
70  * are not part of the source of Date.js, but to use them you can simply copy this
71  * block of code into any script that is included after Date.js and they will also become
72  * globally available on the Date object.  Feel free to add or remove patterns as needed in your code.
73  * <pre><code>
74 Date.patterns = {
75     ISO8601Long:"Y-m-d H:i:s",
76     ISO8601Short:"Y-m-d",
77     ShortDate: "n/j/Y",
78     LongDate: "l, F d, Y",
79     FullDateTime: "l, F d, Y g:i:s A",
80     MonthDay: "F d",
81     ShortTime: "g:i A",
82     LongTime: "g:i:s A",
83     SortableDateTime: "Y-m-d\\TH:i:s",
84     UniversalSortableDateTime: "Y-m-d H:i:sO",
85     YearMonth: "F, Y"
86 };
87 </code></pre>
88  *
89  * Example usage:
90  * <pre><code>
91 var dt = new Date();
92 document.write(dt.format(Date.patterns.ShortDate));
93  </code></pre>
94  */
95
96 /*
97  * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
98  * They generate precompiled functions from date formats instead of parsing and
99  * processing the pattern every time you format a date.  These functions are available
100  * on every Date object (any javascript function).
101  *
102  * The original article and download are here:
103  * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
104  *
105  */
106  
107      
108      // was in core
109     /**
110      Returns the number of milliseconds between this date and date
111      @param {Date} date (optional) Defaults to now
112      @return {Number} The diff in milliseconds
113      @member Date getElapsed
114      */
115 DateExtra = Date; 
116 XObject.extend(Date,
117     {
118         
119         // private
120         parseFunctions : {count:0},
121         // private
122         parseRegexes : [],
123         // private
124         formatFunctions : {count:0},
125             
126             
127         // private
128         // safari setMonth is broken
129          
130         /** Date interval constant 
131         * @static 
132         * @type String */
133         MILLI : "ms",
134         /** Date interval constant 
135         * @static 
136         * @type String */
137         SECOND : "s",
138         /** Date interval constant 
139         * @static 
140         * @type String */
141         MINUTE : "mi",
142         /** Date interval constant 
143         * @static 
144         * @type String */
145         HOUR : "h",
146         /** Date interval constant 
147         * @static 
148         * @type String */
149         DAY : "d",
150         /** Date interval constant 
151         * @static 
152         * @type String */
153         MONTH : "mo",
154         /** Date interval constant 
155         * @static 
156         * @type String */
157         YEAR : "y",
158
159         // private
160         daysInMonth : [31,28,31,30,31,30,31,31,30,31,30,31],
161
162         /**
163          * An array of textual month names.
164          * Override these values for international dates, for example...
165          * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
166          * @type Array
167          * @static
168          */
169         monthNames : [
170             "January",
171             "February",
172             "March",
173             "April",
174             "May",
175             "June",
176             "July",
177             "August",
178             "September",
179             "October",
180             "November",
181             "December"],
182
183         /**
184          * An array of textual day names.
185          * Override these values for international dates, for example...
186          * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
187          * @type Array
188          * @static
189          */
190         dayNames : [
191             "Sunday",
192             "Monday",
193             "Tuesday",
194             "Wednesday",
195             "Thursday",
196             "Friday",
197             "Saturday"],
198
199         // private
200         y2kYear : 50,
201         // private
202         monthNumbers : {
203             Jan:0,
204             Feb:1,
205             Mar:2,
206             Apr:3,
207             May:4,
208             Jun:5,
209             Jul:6,
210             Aug:7,
211             Sep:8,
212             Oct:9,
213             Nov:10,
214             Dec:11},
215         
216         createNewFormat : function(format) {
217             var funcName = "format" + Date.formatFunctions.count++;
218             Date.formatFunctions[format] = funcName;
219             var code = "Date.prototype." + funcName + " = function(){return ";
220             var special = false;
221             var ch = '';
222             for (var i = 0; i < format.length; ++i) {
223                 ch = format.charAt(i);
224                 if (!special && ch == "\\") {
225                     special = true;
226                 }
227                 else if (special) {
228                     special = false;
229                     code += "'" + String.escape(ch) + "' + ";
230                 }
231                 else {
232                     code += Date.getFormatCode(ch);
233                 }
234             }
235             /** eval:var:zzzzzzzzzzzzz */
236             eval(code.substring(0, code.length - 3) + ";}");
237         },
238
239         // private
240         getFormatCode : function(character) {
241             switch (character) {
242             case "d":
243                 return "String.leftPad(this.getDate(), 2, '0') + ";
244             case "D":
245                 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
246             case "j":
247                 return "this.getDate() + ";
248             case "l":
249                 return "Date.dayNames[this.getDay()] + ";
250             case "S":
251                 return "this.getSuffix() + ";
252             case "w":
253                 return "this.getDay() + ";
254             case "z":
255                 return "this.getDayOfYear() + ";
256             case "W":
257                 return "this.getWeekOfYear() + ";
258             case "F":
259                 return "Date.monthNames[this.getMonth()] + ";
260             case "m":
261                 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
262             case "M":
263                 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
264             case "n":
265                 return "(this.getMonth() + 1) + ";
266             case "t":
267                 return "this.getDaysInMonth() + ";
268             case "L":
269                 return "(this.isLeapYear() ? 1 : 0) + ";
270             case "Y":
271                 return "this.getFullYear() + ";
272             case "y":
273                 return "('' + this.getFullYear()).substring(2, 4) + ";
274             case "a":
275                 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
276             case "A":
277                 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
278             case "g":
279                 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
280             case "G":
281                 return "this.getHours() + ";
282             case "h":
283                 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
284             case "H":
285                 return "String.leftPad(this.getHours(), 2, '0') + ";
286             case "i":
287                 return "String.leftPad(this.getMinutes(), 2, '0') + ";
288             case "s":
289                 return "String.leftPad(this.getSeconds(), 2, '0') + ";
290             case "O":
291                 return "this.getGMTOffset() + ";
292             case "T":
293                 return "this.getTimezone() + ";
294             case "Z":
295                 return "(this.getTimezoneOffset() * -60) + ";
296             default:
297                 return "'" + String.escape(character) + "' + ";
298             }
299         },
300
301         /**
302          * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
303          * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates.  Any part of
304          * the date format that is not specified will default to the current date value for that part.  Time parts can also
305          * be specified, but default to 0.  Keep in mind that the input date string must precisely match the specified format
306          * string or the parse operation will fail.
307          * Example Usage:
308         <pre><code>
309         //dt = Fri May 25 2007 (current date)
310         var dt = new Date();
311
312         //dt = Thu May 25 2006 (today's month/day in 2006)
313         dt = Date.parseDate("2006", "Y");
314
315         //dt = Sun Jan 15 2006 (all date parts specified)
316         dt = Date.parseDate("2006-1-15", "Y-m-d");
317
318         //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
319         dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
320         </code></pre>
321          * @param {String} input The unparsed date as a string
322          * @param {String} format The format the date is in
323          * @return {Date} The parsed date
324          * @static
325          */
326         parseDate : function(input, format) {
327             if (Date.parseFunctions[format] == null) {
328                 Date.createParser(format);
329             }
330             var func = Date.parseFunctions[format];
331             return Date[func](input);
332         },
333
334         // private
335         createParser : function(format) {
336             var funcName = "parse" + Date.parseFunctions.count++;
337             var regexNum = Date.parseRegexes.length;
338             var currentGroup = 1;
339             Date.parseFunctions[format] = funcName;
340
341             var code = "Date." + funcName + " = function(input){\n"
342                 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
343                 + "var d = new Date();\n"
344                 + "y = d.getFullYear();\n"
345                 + "m = d.getMonth();\n"
346                 + "d = d.getDate();\n"
347                 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
348                 + "if (results && results.length > 0) {";
349             var regex = "";
350
351             var special = false;
352             var ch = '';
353             for (var i = 0; i < format.length; ++i) {
354                 ch = format.charAt(i);
355                 if (!special && ch == "\\") {
356                     special = true;
357                 }
358                 else if (special) {
359                     special = false;
360                     regex += String.escape(ch);
361                 }
362                 else {
363                     var obj = Date.formatCodeToRegex(ch, currentGroup);
364                     currentGroup += obj.g;
365                     regex += obj.s;
366                     if (obj.g && obj.c) {
367                         code += obj.c;
368                     }
369                 }
370             }
371
372             code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
373                 + "{v = new Date(y, m, d, h, i, s);}\n"
374                 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
375                 + "{v = new Date(y, m, d, h, i);}\n"
376                 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
377                 + "{v = new Date(y, m, d, h);}\n"
378                 + "else if (y >= 0 && m >= 0 && d > 0)\n"
379                 + "{v = new Date(y, m, d);}\n"
380                 + "else if (y >= 0 && m >= 0)\n"
381                 + "{v = new Date(y, m);}\n"
382                 + "else if (y >= 0)\n"
383                 + "{v = new Date(y);}\n"
384                 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
385                 + "    ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
386                 + "        v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
387                 + ";}";
388
389             Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
390              /** eval:var:zzzzzzzzzzzzz */
391             eval(code);
392         },
393
394         // private
395         formatCodeToRegex : function(character, currentGroup) {
396             switch (character) {
397             case "D":
398                 return {g:0,
399                 c:null,
400                 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
401             case "j":
402                 return {g:1,
403                     c:"d = parseInt(results[" + currentGroup + "], 10);\n",
404                     s:"(\\d{1,2})"}; // day of month without leading zeroes
405             case "d":
406                 return {g:1,
407                     c:"d = parseInt(results[" + currentGroup + "], 10);\n",
408                     s:"(\\d{2})"}; // day of month with leading zeroes
409             case "l":
410                 return {g:0,
411                     c:null,
412                     s:"(?:" + Date.dayNames.join("|") + ")"};
413             case "S":
414                 return {g:0,
415                     c:null,
416                     s:"(?:st|nd|rd|th)"};
417             case "w":
418                 return {g:0,
419                     c:null,
420                     s:"\\d"};
421             case "z":
422                 return {g:0,
423                     c:null,
424                     s:"(?:\\d{1,3})"};
425             case "W":
426                 return {g:0,
427                     c:null,
428                     s:"(?:\\d{2})"};
429             case "F":
430                 return {g:1,
431                     c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
432                     s:"(" + Date.monthNames.join("|") + ")"};
433             case "M":
434                 return {g:1,
435                     c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
436                     s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
437             case "n":
438                 return {g:1,
439                     c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
440                     s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
441             case "m":
442                 return {g:1,
443                     c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
444                     s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
445             case "t":
446                 return {g:0,
447                     c:null,
448                     s:"\\d{1,2}"};
449             case "L":
450                 return {g:0,
451                     c:null,
452                     s:"(?:1|0)"};
453             case "Y":
454                 return {g:1,
455                     c:"y = parseInt(results[" + currentGroup + "], 10);\n",
456                     s:"(\\d{4})"};
457             case "y":
458                 return {g:1,
459                     c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
460                         + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
461                     s:"(\\d{1,2})"};
462             case "a":
463                 return {g:1,
464                     c:"if (results[" + currentGroup + "] == 'am') {\n"
465                         + "if (h == 12) { h = 0; }\n"
466                         + "} else { if (h < 12) { h += 12; }}",
467                     s:"(am|pm)"};
468             case "A":
469                 return {g:1,
470                     c:"if (results[" + currentGroup + "] == 'AM') {\n"
471                         + "if (h == 12) { h = 0; }\n"
472                         + "} else { if (h < 12) { h += 12; }}",
473                     s:"(AM|PM)"};
474             case "g":
475             case "G":
476                 return {g:1,
477                     c:"h = parseInt(results[" + currentGroup + "], 10);\n",
478                     s:"(\\d{1,2})"}; // 12/24-hr format  format of an hour without leading zeroes
479             case "h":
480             case "H":
481                 return {g:1,
482                     c:"h = parseInt(results[" + currentGroup + "], 10);\n",
483                     s:"(\\d{2})"}; //  12/24-hr format  format of an hour with leading zeroes
484             case "i":
485                 return {g:1,
486                     c:"i = parseInt(results[" + currentGroup + "], 10);\n",
487                     s:"(\\d{2})"};
488             case "s":
489                 return {g:1,
490                     c:"s = parseInt(results[" + currentGroup + "], 10);\n",
491                     s:"(\\d{2})"};
492             case "O":
493                 return {g:1,
494                     c:[
495                         "o = results[", currentGroup, "];\n",
496                         "var sn = o.substring(0,1);\n", // get + / - sign
497                         "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
498                         "var mn = o.substring(3,5) % 60;\n", // get minutes
499                         "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
500                         "    (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
501                     ].join(""),
502                     s:"([+\-]\\d{4})"};
503             case "T":
504                 return {g:0,
505                     c:null,
506                     s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
507             case "Z":
508                 return {g:1,
509                     c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
510                           + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
511                     s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
512             default:
513             
514                 return {g:0,
515                     c:null,
516                     s:String.escape(character)};
517             }
518         }
519
520         
521     
522 }); // end static date..
523 DateExtra.prototype = DateExtra
524 // now add functions to date..
525 XObject.extend(Date.prototype,
526     {
527
528         getElapsed : function(date) {
529             return Math.abs((date || new Date()).getTime()-this.getTime());
530         },
531          
532
533         /**
534          * Formats a date given the supplied format string
535          * @param {String} format The format string
536          * @return {String} The formatted date
537          * @method
538          */
539
540         
541         format : function(format) {
542             if (Date.formatFunctions[format] == null) {
543                 Date.createNewFormat(format);
544             }
545             var func = Date.formatFunctions[format];
546             return this[func]();
547         },
548
549         // private - why is dataFormat an alias?
550         //format : dateFormat;
551
552         // private
553
554         /**
555          * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
556          * @return {String} The abbreviated timezone name (e.g. 'CST')
557          */
558         getTimezone : function() {
559             return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
560         },
561
562         /**
563          * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
564          * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
565          */
566         getGMTOffset : function() {
567             return (this.getTimezoneOffset() > 0 ? "-" : "+")
568                 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
569                 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
570         },
571
572         /**
573          * Get the numeric day number of the year, adjusted for leap year.
574          * @return {Number} 0 through 364 (365 in leap years)
575          */
576         getDayOfYear : function() {
577             var num = 0;
578             Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
579             for (var i = 0; i < this.getMonth(); ++i) {
580                 num += Date.daysInMonth[i];
581             }
582             return num + this.getDate() - 1;
583         },
584
585         /**
586          * Get the string representation of the numeric week number of the year
587          * (equivalent to the format specifier 'W').
588          * @return {String} '00' through '52'
589          */
590         getWeekOfYear : function() {
591             // Skip to Thursday of this week
592             var now = this.getDayOfYear() + (4 - this.getDay());
593             // Find the first Thursday of the year
594             var jan1 = new Date(this.getFullYear(), 0, 1);
595             var then = (7 - jan1.getDay() + 4);
596             return String.leftPad(((now - then) / 7) + 1, 2, "0");
597         },
598
599         /**
600          * Whether or not the current date is in a leap year.
601          * @return {Boolean} True if the current date is in a leap year, else false
602          */
603         isLeapYear : function() {
604             var year = this.getFullYear();
605             return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
606         },
607
608         /**
609          * Get the first day of the current month, adjusted for leap year.  The returned value
610          * is the numeric day index within the week (0-6) which can be used in conjunction with
611          * the {@link #monthNames} array to retrieve the textual day name.
612          * Example:
613          *<pre><code>
614         var dt = new Date('1/10/2007');
615         document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
616         </code></pre>
617          * @return {Number} The day number (0-6)
618          */
619         getFirstDayOfMonth : function() {
620             var day = (this.getDay() - (this.getDate() - 1)) % 7;
621             return (day < 0) ? (day + 7) : day;
622         },
623
624         /**
625          * Get the last day of the current month, adjusted for leap year.  The returned value
626          * is the numeric day index within the week (0-6) which can be used in conjunction with
627          * the {@link #monthNames} array to retrieve the textual day name.
628          * Example:
629          *<pre><code>
630         var dt = new Date('1/10/2007');
631         document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
632         </code></pre>
633          * @return {Number} The day number (0-6)
634          */
635         getLastDayOfMonth : function() {
636             var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
637             return (day < 0) ? (day + 7) : day;
638         },
639
640
641         /**
642          * Get the first date of this date's month
643          * @return {Date}
644          */
645         getFirstDateOfMonth : function() {
646             return new Date(this.getFullYear(), this.getMonth(), 1);
647         },
648
649         /**
650          * Get the last date of this date's month
651          * @return {Date}
652          */
653         getLastDateOfMonth : function() {
654             return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
655         },
656         /**
657          * Get the number of days in the current month, adjusted for leap year.
658          * @return {Number} The number of days in the month
659          */
660         getDaysInMonth : function() {
661             Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
662             return Date.daysInMonth[this.getMonth()];
663         },
664
665         /**
666          * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
667          * @return {String} 'st, 'nd', 'rd' or 'th'
668          */
669         getSuffix : function() {
670             switch (this.getDate()) {
671                 case 1:
672                 case 21:
673                 case 31:
674                     return "st";
675                 case 2:
676                 case 22:
677                     return "nd";
678                 case 3:
679                 case 23:
680                     return "rd";
681                 default:
682                     return "th";
683             }
684         },
685
686
687         /**
688          * Creates and returns a new Date instance with the exact same date value as the called instance.
689          * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
690          * variable will also be changed.  When the intention is to create a new variable that will not
691          * modify the original instance, you should create a clone.
692          *
693          * Example of correctly cloning a date:
694          * <pre><code>
695         //wrong way:
696         var orig = new Date('10/1/2006');
697         var copy = orig;
698         copy.setDate(5);
699         document.write(orig);  //returns 'Thu Oct 05 2006'!
700
701         //correct way:
702         var orig = new Date('10/1/2006');
703         var copy = orig.clone();
704         copy.setDate(5);
705         document.write(orig);  //returns 'Thu Oct 01 2006'
706         </code></pre>
707          * @return {Date} The new Date instance
708          */
709         clone : function() {
710             return new Date(this.getTime());
711         },
712
713         /**
714          * Clears any time information from this date
715          @param {Boolean} clone true to create a clone of this date, clear the time and return it
716          @return {Date} this or the clone
717          */
718         clearTime : function(clone){
719             if(clone){
720                 return this.clone().clearTime();
721             }
722             this.setHours(0);
723             this.setMinutes(0);
724             this.setSeconds(0);
725             this.setMilliseconds(0);
726             return this;
727         },
728
729         /**
730          * Provides a convenient method of performing basic date arithmetic.  This method
731          * does not modify the Date instance being called - it creates and returns
732          * a new Date instance containing the resulting date value.
733          *
734          * Examples:
735          * <pre><code>
736         //Basic usage:
737         var dt = new Date('10/29/2006').add(Date.DAY, 5);
738         document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
739
740         //Negative values will subtract correctly:
741         var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
742         document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
743
744         //You can even chain several calls together in one line!
745         var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
746         document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
747          </code></pre>
748          *
749          * @param {String} interval   A valid date interval enum value
750          * @param {Number} value      The amount to add to the current date
751          * @return {Date} The new Date instance
752          */
753         add : function(interval, value){
754           var d = this.clone();
755           if (!interval || value === 0) return d;
756           switch(interval.toLowerCase()){
757             case Date.MILLI:
758               d.setMilliseconds(this.getMilliseconds() + value);
759               break;
760             case Date.SECOND:
761               d.setSeconds(this.getSeconds() + value);
762               break;
763             case Date.MINUTE:
764               d.setMinutes(this.getMinutes() + value);
765               break;
766             case Date.HOUR:
767               d.setHours(this.getHours() + value);
768               break;
769             case Date.DAY:
770               d.setDate(this.getDate() + value);
771               break;
772             case Date.MONTH:
773               var day = this.getDate();
774               if(day > 28){
775                   day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
776               }
777               d.setDate(day);
778               d.setMonth(this.getMonth() + value);
779               break;
780             case Date.YEAR:
781               d.setFullYear(this.getFullYear() + value);
782               break;
783           }
784           return d;
785         }
786
787 });