4 * Copyright(c) 2006-2007, Ext JS, LLC.
6 * Originally Released Under LGPL - original licence link has changed is not relivant.
9 * <script type="text/javascript">
11 // usage: Seed.include('Date.js')
14 String = imports.String.String;
15 XObject = imports.XObject.XObject;
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.
25 * Following is the list of all currently supported formats:
28 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
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)
61 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
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
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.
75 ISO8601Long:"Y-m-d H:i:s",
78 LongDate: "l, F d, Y",
79 FullDateTime: "l, F d, Y g:i:s A",
83 SortableDateTime: "Y-m-d\\TH:i:s",
84 UniversalSortableDateTime: "Y-m-d H:i:sO",
92 document.write(dt.format(Date.patterns.ShortDate));
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).
102 * The original article and download are here:
103 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
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
115 Date = XObject.extend(Date,
119 parseFunctions : {count:0},
123 formatFunctions : {count:0},
127 // safari setMonth is broken
129 /** Date interval constant
133 /** Date interval constant
137 /** Date interval constant
141 /** Date interval constant
145 /** Date interval constant
149 /** Date interval constant
153 /** Date interval constant
159 daysInMonth : [31,28,31,30,31,30,31,31,30,31,30,31],
162 * An array of textual month names.
163 * Override these values for international dates, for example...
164 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
183 * An array of textual day names.
184 * Override these values for international dates, for example...
185 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
215 createNewFormat : function(format) {
216 var funcName = "format" + Date.formatFunctions.count++;
217 Date.formatFunctions[format] = funcName;
218 var code = "Date.prototype." + funcName + " = function(){return ";
221 for (var i = 0; i < format.length; ++i) {
222 ch = format.charAt(i);
223 if (!special && ch == "\\") {
228 code += "'" + String.escape(ch) + "' + ";
231 code += Date.getFormatCode(ch);
234 /** eval:var:zzzzzzzzzzzzz */
235 eval(code.substring(0, code.length - 3) + ";}");
239 getFormatCode : function(character) {
242 return "String.leftPad(this.getDate(), 2, '0') + ";
244 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
246 return "this.getDate() + ";
248 return "Date.dayNames[this.getDay()] + ";
250 return "this.getSuffix() + ";
252 return "this.getDay() + ";
254 return "this.getDayOfYear() + ";
256 return "this.getWeekOfYear() + ";
258 return "Date.monthNames[this.getMonth()] + ";
260 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
262 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
264 return "(this.getMonth() + 1) + ";
266 return "this.getDaysInMonth() + ";
268 return "(this.isLeapYear() ? 1 : 0) + ";
270 return "this.getFullYear() + ";
272 return "('' + this.getFullYear()).substring(2, 4) + ";
274 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
276 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
278 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
280 return "this.getHours() + ";
282 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
284 return "String.leftPad(this.getHours(), 2, '0') + ";
286 return "String.leftPad(this.getMinutes(), 2, '0') + ";
288 return "String.leftPad(this.getSeconds(), 2, '0') + ";
290 return "this.getGMTOffset() + ";
292 return "this.getTimezone() + ";
294 return "(this.getTimezoneOffset() * -60) + ";
296 return "'" + String.escape(character) + "' + ";
301 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
302 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
303 * the date format that is not specified will default to the current date value for that part. Time parts can also
304 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
305 * string or the parse operation will fail.
308 //dt = Fri May 25 2007 (current date)
311 //dt = Thu May 25 2006 (today's month/day in 2006)
312 dt = Date.parseDate("2006", "Y");
314 //dt = Sun Jan 15 2006 (all date parts specified)
315 dt = Date.parseDate("2006-1-15", "Y-m-d");
317 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
318 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
320 * @param {String} input The unparsed date as a string
321 * @param {String} format The format the date is in
322 * @return {Date} The parsed date
325 parseDate : function(input, format) {
326 if (Date.parseFunctions[format] == null) {
327 Date.createParser(format);
329 var func = Date.parseFunctions[format];
330 return Date[func](input);
336 createParser : function(format) {
337 var funcName = "parse" + Date.parseFunctions.count++;
338 var regexNum = Date.parseRegexes.length;
339 var currentGroup = 1;
340 Date.parseFunctions[format] = funcName;
342 var code = "Date." + funcName + " = function(input){\n"
343 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
344 + "var d = new Date();\n"
345 + "y = d.getFullYear();\n"
346 + "m = d.getMonth();\n"
347 + "d = d.getDate();\n"
348 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
349 + "if (results && results.length > 0) {";
354 for (var i = 0; i < format.length; ++i) {
355 ch = format.charAt(i);
356 if (!special && ch == "\\") {
361 regex += String.escape(ch);
364 var obj = Date.formatCodeToRegex(ch, currentGroup);
365 currentGroup += obj.g;
367 if (obj.g && obj.c) {
373 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
374 + "{v = new Date(y, m, d, h, i, s);}\n"
375 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
376 + "{v = new Date(y, m, d, h, i);}\n"
377 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
378 + "{v = new Date(y, m, d, h);}\n"
379 + "else if (y >= 0 && m >= 0 && d > 0)\n"
380 + "{v = new Date(y, m, d);}\n"
381 + "else if (y >= 0 && m >= 0)\n"
382 + "{v = new Date(y, m);}\n"
383 + "else if (y >= 0)\n"
384 + "{v = new Date(y);}\n"
385 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
386 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
387 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
390 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
391 /** eval:var:zzzzzzzzzzzzz */
396 formatCodeToRegex : function(character, currentGroup) {
401 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
404 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
405 s:"(\\d{1,2})"}; // day of month without leading zeroes
408 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
409 s:"(\\d{2})"}; // day of month with leading zeroes
413 s:"(?:" + Date.dayNames.join("|") + ")"};
417 s:"(?:st|nd|rd|th)"};
432 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
433 s:"(" + Date.monthNames.join("|") + ")"};
436 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
437 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
440 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
441 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
444 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
445 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
456 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
460 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
461 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
465 c:"if (results[" + currentGroup + "] == 'am') {\n"
466 + "if (h == 12) { h = 0; }\n"
467 + "} else { if (h < 12) { h += 12; }}",
471 c:"if (results[" + currentGroup + "] == 'AM') {\n"
472 + "if (h == 12) { h = 0; }\n"
473 + "} else { if (h < 12) { h += 12; }}",
478 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
479 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
483 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
484 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
487 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
491 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
496 "o = results[", currentGroup, "];\n",
497 "var sn = o.substring(0,1);\n", // get + / - sign
498 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
499 "var mn = o.substring(3,5) % 60;\n", // get minutes
500 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
501 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
507 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
510 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
511 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
512 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
517 s:String.escape(character)};
523 }); // end static date..
525 // now add functions to date..
526 XObject.extend(Date.prototype,
529 getElapsed : function(date) {
530 return Math.abs((date || new Date()).getTime()-this.getTime());
535 * Formats a date given the supplied format string
536 * @param {String} format The format string
537 * @return {String} The formatted date
542 format : function(format) {
543 if (Date.formatFunctions[format] == null) {
544 Date.createNewFormat(format);
546 var func = Date.formatFunctions[format];
550 // private - why is dataFormat an alias?
551 //format : dateFormat;
556 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
557 * @return {String} The abbreviated timezone name (e.g. 'CST')
559 getTimezone : function() {
560 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
564 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
565 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
567 getGMTOffset : function() {
568 return (this.getTimezoneOffset() > 0 ? "-" : "+")
569 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
570 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
574 * Get the numeric day number of the year, adjusted for leap year.
575 * @return {Number} 0 through 364 (365 in leap years)
577 getDayOfYear : function() {
579 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
580 for (var i = 0; i < this.getMonth(); ++i) {
581 num += Date.daysInMonth[i];
583 return num + this.getDate() - 1;
587 * Get the string representation of the numeric week number of the year
588 * (equivalent to the format specifier 'W').
589 * @return {String} '00' through '52'
591 getWeekOfYear : function() {
592 // Skip to Thursday of this week
593 var now = this.getDayOfYear() + (4 - this.getDay());
594 // Find the first Thursday of the year
595 var jan1 = new Date(this.getFullYear(), 0, 1);
596 var then = (7 - jan1.getDay() + 4);
597 return String.leftPad(((now - then) / 7) + 1, 2, "0");
601 * Whether or not the current date is in a leap year.
602 * @return {Boolean} True if the current date is in a leap year, else false
604 isLeapYear : function() {
605 var year = this.getFullYear();
606 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
610 * Get the first day of the current month, adjusted for leap year. The returned value
611 * is the numeric day index within the week (0-6) which can be used in conjunction with
612 * the {@link #monthNames} array to retrieve the textual day name.
615 var dt = new Date('1/10/2007');
616 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
618 * @return {Number} The day number (0-6)
620 getFirstDayOfMonth : function() {
621 var day = (this.getDay() - (this.getDate() - 1)) % 7;
622 return (day < 0) ? (day + 7) : day;
626 * Get the last day of the current month, adjusted for leap year. The returned value
627 * is the numeric day index within the week (0-6) which can be used in conjunction with
628 * the {@link #monthNames} array to retrieve the textual day name.
631 var dt = new Date('1/10/2007');
632 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
634 * @return {Number} The day number (0-6)
636 getLastDayOfMonth : function() {
637 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
638 return (day < 0) ? (day + 7) : day;
643 * Get the first date of this date's month
646 getFirstDateOfMonth : function() {
647 return new Date(this.getFullYear(), this.getMonth(), 1);
651 * Get the last date of this date's month
654 getLastDateOfMonth : function() {
655 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
658 * Get the number of days in the current month, adjusted for leap year.
659 * @return {Number} The number of days in the month
661 getDaysInMonth : function() {
662 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
663 return Date.daysInMonth[this.getMonth()];
667 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
668 * @return {String} 'st, 'nd', 'rd' or 'th'
670 getSuffix : function() {
671 switch (this.getDate()) {
689 * Creates and returns a new Date instance with the exact same date value as the called instance.
690 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
691 * variable will also be changed. When the intention is to create a new variable that will not
692 * modify the original instance, you should create a clone.
694 * Example of correctly cloning a date:
697 var orig = new Date('10/1/2006');
700 document.write(orig); //returns 'Thu Oct 05 2006'!
703 var orig = new Date('10/1/2006');
704 var copy = orig.clone();
706 document.write(orig); //returns 'Thu Oct 01 2006'
708 * @return {Date} The new Date instance
711 return new Date(this.getTime());
715 * Clears any time information from this date
716 @param {Boolean} clone true to create a clone of this date, clear the time and return it
717 @return {Date} this or the clone
719 clearTime : function(clone){
721 return this.clone().clearTime();
726 this.setMilliseconds(0);
731 * Provides a convenient method of performing basic date arithmetic. This method
732 * does not modify the Date instance being called - it creates and returns
733 * a new Date instance containing the resulting date value.
738 var dt = new Date('10/29/2006').add(Date.DAY, 5);
739 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
741 //Negative values will subtract correctly:
742 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
743 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
745 //You can even chain several calls together in one line!
746 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
747 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
750 * @param {String} interval A valid date interval enum value
751 * @param {Number} value The amount to add to the current date
752 * @return {Date} The new Date instance
754 add : function(interval, value){
755 var d = this.clone();
756 if (!interval || value === 0) return d;
757 switch(interval.toLowerCase()){
759 d.setMilliseconds(this.getMilliseconds() + value);
762 d.setSeconds(this.getSeconds() + value);
765 d.setMinutes(this.getMinutes() + value);
768 d.setHours(this.getHours() + value);
771 d.setDate(this.getDate() + value);
774 var day = this.getDate();
776 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
779 d.setMonth(this.getMonth() + value);
782 d.setFullYear(this.getFullYear() + value);