JSDOC/ScopeNamer.js
[app.jsdoc] / Date.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: Seed.include('Date.js')
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 Date = XObject.extend(Date,
111     {
112         /**
113          * @static
114          * @private
115          */
116         parseFunctions : {count:0},
117         /** @private */
118         parseRegexes : [],
119         /** @private */
120         formatFunctions : {count:0},
121             
122             
123         // private
124         // safari setMonth is broken
125          
126         /** Date interval constant 
127         * @static 
128         * @type String */
129         MILLI : "ms",
130         /** Date interval constant 
131         * @static 
132         * @type String */
133         SECOND : "s",
134         /** Date interval constant 
135         * @static 
136         * @type String */
137         MINUTE : "mi",
138         /** Date interval constant 
139         * @static 
140         * @type String */
141         HOUR : "h",
142         /** Date interval constant 
143         * @static 
144         * @type String */
145         DAY : "d",
146         /** Date interval constant 
147         * @static 
148         * @type String */
149         MONTH : "mo",
150         /** Date interval constant 
151         * @static 
152         * @type String */
153         YEAR : "y",
154
155         // private
156         daysInMonth : [31,28,31,30,31,30,31,31,30,31,30,31],
157
158         /**
159          * An array of textual month names.
160          * Override these values for international dates, for example...
161          * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
162          * @type Array
163          * @static
164          */
165         monthNames : [
166             "January",
167             "February",
168             "March",
169             "April",
170             "May",
171             "June",
172             "July",
173             "August",
174             "September",
175             "October",
176             "November",
177             "December"],
178
179         /**
180          * An array of textual day names.
181          * Override these values for international dates, for example...
182          * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
183          * @type Array
184          * @static
185          */
186         dayNames : [
187             "Sunday",
188             "Monday",
189             "Tuesday",
190             "Wednesday",
191             "Thursday",
192             "Friday",
193             "Saturday"],
194
195         // private
196         y2kYear : 50,
197         // private
198         monthNumbers : {
199             Jan:0,
200             Feb:1,
201             Mar:2,
202             Apr:3,
203             May:4,
204             Jun:5,
205             Jul:6,
206             Aug:7,
207             Sep:8,
208             Oct:9,
209             Nov:10,
210             Dec:11},
211         
212         createNewFormat : function(format) {
213             var funcName = "format" + Date.formatFunctions.count++;
214             Date.formatFunctions[format] = funcName;
215             var code = "Date.prototype." + funcName + " = function(){return ";
216             var special = false;
217             var ch = '';
218             for (var i = 0; i < format.length; ++i) {
219                 ch = format.charAt(i);
220                 if (!special && ch == "\\") {
221                     special = true;
222                 }
223                 else if (special) {
224                     special = false;
225                     code += "'" + String.escape(ch) + "' + ";
226                 }
227                 else {
228                     code += Date.getFormatCode(ch);
229                 }
230             }
231             /** eval:var:zzzzzzzzzzzzz */
232             eval(code.substring(0, code.length - 3) + ";}");
233         },
234
235         // private
236         getFormatCode : function(character) {
237             switch (character) {
238             case "d":
239                 return "String.leftPad(this.getDate(), 2, '0') + ";
240             case "D":
241                 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
242             case "j":
243                 return "this.getDate() + ";
244             case "l":
245                 return "Date.dayNames[this.getDay()] + ";
246             case "S":
247                 return "this.getSuffix() + ";
248             case "w":
249                 return "this.getDay() + ";
250             case "z":
251                 return "this.getDayOfYear() + ";
252             case "W":
253                 return "this.getWeekOfYear() + ";
254             case "F":
255                 return "Date.monthNames[this.getMonth()] + ";
256             case "m":
257                 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
258             case "M":
259                 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
260             case "n":
261                 return "(this.getMonth() + 1) + ";
262             case "t":
263                 return "this.getDaysInMonth() + ";
264             case "L":
265                 return "(this.isLeapYear() ? 1 : 0) + ";
266             case "Y":
267                 return "this.getFullYear() + ";
268             case "y":
269                 return "('' + this.getFullYear()).substring(2, 4) + ";
270             case "a":
271                 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
272             case "A":
273                 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
274             case "g":
275                 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
276             case "G":
277                 return "this.getHours() + ";
278             case "h":
279                 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
280             case "H":
281                 return "String.leftPad(this.getHours(), 2, '0') + ";
282             case "i":
283                 return "String.leftPad(this.getMinutes(), 2, '0') + ";
284             case "s":
285                 return "String.leftPad(this.getSeconds(), 2, '0') + ";
286             case "O":
287                 return "this.getGMTOffset() + ";
288             case "T":
289                 return "this.getTimezone() + ";
290             case "Z":
291                 return "(this.getTimezoneOffset() * -60) + ";
292             default:
293                 return "'" + String.escape(character) + "' + ";
294             }
295         },
296
297         /**
298          * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
299          * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates.  Any part of
300          * the date format that is not specified will default to the current date value for that part.  Time parts can also
301          * be specified, but default to 0.  Keep in mind that the input date string must precisely match the specified format
302          * string or the parse operation will fail.
303          * Example Usage:
304         <pre><code>
305         //dt = Fri May 25 2007 (current date)
306         var dt = new Date();
307
308         //dt = Thu May 25 2006 (today's month/day in 2006)
309         dt = Date.parseDate("2006", "Y");
310
311         //dt = Sun Jan 15 2006 (all date parts specified)
312         dt = Date.parseDate("2006-1-15", "Y-m-d");
313
314         //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
315         dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
316         </code></pre>
317          * @param {String} input The unparsed date as a string
318          * @param {String} format The format the date is in
319          * @return {Date} The parsed date
320          * @static
321          */
322         parseDate : function(input, format) {
323             if (Date.parseFunctions[format] == null) {
324                 Date.createParser(format);
325             }
326             var func = Date.parseFunctions[format];
327             return Date[func](input);
328         },
329
330         /**
331         * @private
332         */
333         createParser : function(format) {
334             var funcName = "parse" + Date.parseFunctions.count++;
335             var regexNum = Date.parseRegexes.length;
336             var currentGroup = 1;
337             Date.parseFunctions[format] = funcName;
338
339             var code = "Date." + funcName + " = function(input){\n"
340                 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
341                 + "var d = new Date();\n"
342                 + "y = d.getFullYear();\n"
343                 + "m = d.getMonth();\n"
344                 + "d = d.getDate();\n"
345                 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
346                 + "if (results && results.length > 0) {";
347             var regex = "";
348
349             var special = false;
350             var ch = '';
351             for (var i = 0; i < format.length; ++i) {
352                 ch = format.charAt(i);
353                 if (!special && ch == "\\") {
354                     special = true;
355                 }
356                 else if (special) {
357                     special = false;
358                     regex += String.escape(ch);
359                 }
360                 else {
361                     var obj = Date.formatCodeToRegex(ch, currentGroup);
362                     currentGroup += obj.g;
363                     regex += obj.s;
364                     if (obj.g && obj.c) {
365                         code += obj.c;
366                     }
367                 }
368             }
369
370             code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
371                 + "{v = new Date(y, m, d, h, i, s);}\n"
372                 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
373                 + "{v = new Date(y, m, d, h, i);}\n"
374                 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
375                 + "{v = new Date(y, m, d, h);}\n"
376                 + "else if (y >= 0 && m >= 0 && d > 0)\n"
377                 + "{v = new Date(y, m, d);}\n"
378                 + "else if (y >= 0 && m >= 0)\n"
379                 + "{v = new Date(y, m);}\n"
380                 + "else if (y >= 0)\n"
381                 + "{v = new Date(y);}\n"
382                 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
383                 + "    ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
384                 + "        v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
385                 + ";}";
386
387             Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
388              /** eval:var:zzzzzzzzzzzzz */
389             eval(code);
390         },
391
392         // private
393         formatCodeToRegex : function(character, currentGroup) {
394             switch (character) {
395             case "D":
396                 return {
397                     g:0,
398                     c:null,
399                     s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"
400                 };
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
524 // now add functions to date..
525 XObject.extend(Date.prototype,
526     {
527         /**
528         Returns the number of milliseconds between this date and date
529         @param {Date} date (optional) Defaults to now
530         @return {Number} The diff in milliseconds
531         @member Date getElapsed
532         */
533         getElapsed : function(date) {
534             return Math.abs((date || new Date()).getTime()-this.getTime());
535         },
536          
537
538         /**
539          * Formats a date given the supplied format string
540          * @param {String} format The format string
541          * @return {String} The formatted date
542          * @method
543          */
544
545         
546         format : function(format) {
547             if (Date.formatFunctions[format] == null) {
548                 Date.createNewFormat(format);
549             }
550             var func = Date.formatFunctions[format];
551             return this[func]();
552         },
553
554         // private - why is dataFormat an alias?
555         //format : dateFormat;
556
557         // private
558
559         /**
560          * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
561          * @return {String} The abbreviated timezone name (e.g. 'CST')
562          */
563         getTimezone : function() {
564             return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
565         },
566
567         /**
568          * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
569          * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
570          */
571         getGMTOffset : function() {
572             return (this.getTimezoneOffset() > 0 ? "-" : "+")
573                 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
574                 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
575         },
576
577         /**
578          * Get the numeric day number of the year, adjusted for leap year.
579          * @return {Number} 0 through 364 (365 in leap years)
580          */
581         getDayOfYear : function() {
582             var num = 0;
583             Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
584             for (var i = 0; i < this.getMonth(); ++i) {
585                 num += Date.daysInMonth[i];
586             }
587             return num + this.getDate() - 1;
588         },
589
590         /**
591          * Get the string representation of the numeric week number of the year
592          * (equivalent to the format specifier 'W').
593          * @return {String} '00' through '52'
594          */
595         getWeekOfYear : function() {
596             // Skip to Thursday of this week
597             var now = this.getDayOfYear() + (4 - this.getDay());
598             // Find the first Thursday of the year
599             var jan1 = new Date(this.getFullYear(), 0, 1);
600             var then = (7 - jan1.getDay() + 4);
601             return String.leftPad(((now - then) / 7) + 1, 2, "0");
602         },
603
604         /**
605          * Whether or not the current date is in a leap year.
606          * @return {Boolean} True if the current date is in a leap year, else false
607          */
608         isLeapYear : function() {
609             var year = this.getFullYear();
610             return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
611         },
612
613         /**
614          * Get the first day of the current month, adjusted for leap year.  The returned value
615          * is the numeric day index within the week (0-6) which can be used in conjunction with
616          * the {@link #monthNames} array to retrieve the textual day name.
617          * Example:
618          *<pre><code>
619         var dt = new Date('1/10/2007');
620         document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
621         </code></pre>
622          * @return {Number} The day number (0-6)
623          */
624         getFirstDayOfMonth : function() {
625             var day = (this.getDay() - (this.getDate() - 1)) % 7;
626             return (day < 0) ? (day + 7) : day;
627         },
628
629         /**
630          * Get the last day of the current month, adjusted for leap year.  The returned value
631          * is the numeric day index within the week (0-6) which can be used in conjunction with
632          * the {@link #monthNames} array to retrieve the textual day name.
633          * Example:
634          *<pre><code>
635         var dt = new Date('1/10/2007');
636         document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
637         </code></pre>
638          * @return {Number} The day number (0-6)
639          */
640         getLastDayOfMonth : function() {
641             var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
642             return (day < 0) ? (day + 7) : day;
643         },
644
645
646         /**
647          * Get the first date of this date's month
648          * @return {Date}
649          */
650         getFirstDateOfMonth : function() {
651             return new Date(this.getFullYear(), this.getMonth(), 1);
652         },
653
654         /**
655          * Get the last date of this date's month
656          * @return {Date}
657          */
658         getLastDateOfMonth : function() {
659             return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
660         },
661         /**
662          * Get the number of days in the current month, adjusted for leap year.
663          * @return {Number} The number of days in the month
664          */
665         getDaysInMonth : function()
666         {
667             Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
668             return Date.daysInMonth[this.getMonth()];
669         },
670
671         /**
672          * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
673          * @return {String} 'st, 'nd', 'rd' or 'th'
674          */
675         getSuffix : function()
676         {
677             switch (this.getDate()) {
678                 case 1:
679                 case 21:
680                 case 31:
681                     return "st";
682                 case 2:
683                 case 22:
684                     return "nd";
685                 case 3:
686                 case 23:
687                     return "rd";
688                 default:
689                     return "th";
690             }
691         },
692
693
694         /**
695          * Creates and returns a new Date instance with the exact same date value as the called instance.
696          * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
697          * variable will also be changed.  When the intention is to create a new variable that will not
698          * modify the original instance, you should create a clone.
699          *
700          * Example of correctly cloning a date:
701          * <pre><code>
702         //wrong way:
703         var orig = new Date('10/1/2006');
704         var copy = orig;
705         copy.setDate(5);
706         document.write(orig);  //returns 'Thu Oct 05 2006'!
707
708         //correct way:
709         var orig = new Date('10/1/2006');
710         var copy = orig.clone();
711         copy.setDate(5);
712         document.write(orig);  //returns 'Thu Oct 01 2006'
713         </code></pre>
714          * @return {Date} The new Date instance
715          */
716         clone : function()
717         {
718             return new Date(this.getTime());
719         },
720
721         /**
722          * Clears any time information from this date
723          @param {Boolean} clone true to create a clone of this date, clear the time and return it
724          @return {Date} this or the clone
725          */
726         clearTime : function(clone)
727         {
728             if(clone){
729                 return this.clone().clearTime();
730             }
731             this.setHours(0);
732             this.setMinutes(0);
733             this.setSeconds(0);
734             this.setMilliseconds(0);
735             return this;
736         },
737
738         /**
739          * Provides a convenient method of performing basic date arithmetic.  This method
740          * does not modify the Date instance being called - it creates and returns
741          * a new Date instance containing the resulting date value.
742          *
743          * Examples:
744          * <pre><code>
745         //Basic usage:
746         var dt = new Date('10/29/2006').add(Date.DAY, 5);
747         document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
748
749         //Negative values will subtract correctly:
750         var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
751         document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
752
753         //You can even chain several calls together in one line!
754         var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
755         document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
756          </code></pre>
757          *
758          * @param {String} interval   A valid date interval enum value
759          * @param {Number} value      The amount to add to the current date
760          * @return {Date} The new Date instance
761          */
762         add : function(interval, value)
763         {
764             var d = this.clone();
765             if (!interval || value === 0) return d;
766             switch(interval.toLowerCase()){
767                 case Date.MILLI:
768                     d.setMilliseconds(this.getMilliseconds() + value);
769                     break;
770                 
771                 case Date.SECOND:
772                     d.setSeconds(this.getSeconds() + value);
773                     break;
774                 
775                 case Date.MINUTE:
776                     d.setMinutes(this.getMinutes() + value);
777                     break;
778                 
779                 case Date.HOUR:
780                     d.setHours(this.getHours() + value);
781                     break;
782                 
783                 case Date.DAY:
784                     d.setDate(this.getDate() + value);
785                     break;
786                 
787                 case Date.MONTH:
788                     var day = this.getDate();
789                     if(day > 28){
790                         day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
791                     }
792                     d.setDate(day);
793                     d.setMonth(this.getMonth() + value);
794                     break;
795                 
796                 case Date.YEAR:
797                     d.setFullYear(this.getFullYear() + value);
798                     break;
799                 
800             }
801             return d;
802         }
803
804 });