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">
15 * The date parsing and format syntax is a subset of
16 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
17 * supported will provide results equivalent to their PHP versions.
19 * Following is the list of all currently supported formats:
22 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
24 Format Output Description
25 ------ ---------- --------------------------------------------------------------
26 d 10 Day of the month, 2 digits with leading zeros
27 D Wed A textual representation of a day, three letters
28 j 10 Day of the month without leading zeros
29 l Wednesday A full textual representation of the day of the week
30 S th English ordinal day of month suffix, 2 chars (use with j)
31 w 3 Numeric representation of the day of the week
32 z 9 The julian date, or day of the year (0-365)
33 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
34 F January A full textual representation of the month
35 m 01 Numeric representation of a month, with leading zeros
36 M Jan Month name abbreviation, three letters
37 n 1 Numeric representation of a month, without leading zeros
38 t 31 Number of days in the given month
39 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
40 Y 2007 A full numeric representation of a year, 4 digits
41 y 07 A two digit representation of a year
42 a pm Lowercase Ante meridiem and Post meridiem
43 A PM Uppercase Ante meridiem and Post meridiem
44 g 3 12-hour format of an hour without leading zeros
45 G 15 24-hour format of an hour without leading zeros
46 h 03 12-hour format of an hour with leading zeros
47 H 15 24-hour format of an hour with leading zeros
48 i 05 Minutes with leading zeros
49 s 01 Seconds, with leading zeros
50 O -0600 Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
51 P -06:00 Difference to Greenwich time (GMT) with colon between hours and minutes
52 T CST Timezone setting of the machine running the code
53 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
56 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
58 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
59 document.write(dt.format('Y-m-d')); //2007-01-10
60 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
61 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
64 * Here are some standard date/time patterns that you might find helpful. They
65 * are not part of the source of Date.js, but to use them you can simply copy this
66 * block of code into any script that is included after Date.js and they will also become
67 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
70 ISO8601Long:"Y-m-d H:i:s",
73 LongDate: "l, F d, Y",
74 FullDateTime: "l, F d, Y g:i:s A",
78 SortableDateTime: "Y-m-d\\TH:i:s",
79 UniversalSortableDateTime: "Y-m-d H:i:sO",
87 document.write(dt.format(Date.patterns.ShortDate));
92 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
93 * They generate precompiled functions from date formats instead of parsing and
94 * processing the pattern every time you format a date. These functions are available
95 * on every Date object (any javascript function).
97 * The original article and download are here:
98 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
105 Returns the number of milliseconds between this date and date
106 @param {Date} date (optional) Defaults to now
107 @return {Number} The diff in milliseconds
108 @member Date getElapsed
110 Date.prototype.getElapsed = function(date) {
111 return Math.abs((date || new Date()).getTime()-this.getTime());
113 // was in date file..
117 Date.parseFunctions = {count:0};
119 Date.parseRegexes = [];
121 Date.formatFunctions = {count:0};
124 Date.prototype.dateFormat = function(format) {
125 if (Date.formatFunctions[format] == null) {
126 Date.createNewFormat(format);
128 var func = Date.formatFunctions[format];
134 * Formats a date given the supplied format string
135 * @param {String} format The format string
136 * @return {String} The formatted date
139 Date.prototype.format = Date.prototype.dateFormat;
142 Date.createNewFormat = function(format) {
143 var funcName = "format" + Date.formatFunctions.count++;
144 Date.formatFunctions[format] = funcName;
145 var code = "Date.prototype." + funcName + " = function(){return ";
148 for (var i = 0; i < format.length; ++i) {
149 ch = format.charAt(i);
150 if (!special && ch == "\\") {
155 code += "'" + String.escape(ch) + "' + ";
158 code += Date.getFormatCode(ch);
161 /** eval:var:zzzzzzzzzzzzz */
162 eval(code.substring(0, code.length - 3) + ";}");
166 Date.getFormatCode = function(character) {
169 return "String.leftPad(this.getDate(), 2, '0') + ";
171 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
173 return "this.getDate() + ";
175 return "Date.dayNames[this.getDay()] + ";
177 return "this.getSuffix() + ";
179 return "this.getDay() + ";
181 return "this.getDayOfYear() + ";
183 return "this.getWeekOfYear() + ";
185 return "Date.monthNames[this.getMonth()] + ";
187 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
189 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
191 return "(this.getMonth() + 1) + ";
193 return "this.getDaysInMonth() + ";
195 return "(this.isLeapYear() ? 1 : 0) + ";
197 return "this.getFullYear() + ";
199 return "('' + this.getFullYear()).substring(2, 4) + ";
201 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
203 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
205 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
207 return "this.getHours() + ";
209 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
211 return "String.leftPad(this.getHours(), 2, '0') + ";
213 return "String.leftPad(this.getMinutes(), 2, '0') + ";
215 return "String.leftPad(this.getSeconds(), 2, '0') + ";
217 return "this.getGMTOffset() + ";
219 return "this.getGMTColonOffset() + ";
221 return "this.getTimezone() + ";
223 return "(this.getTimezoneOffset() * -60) + ";
225 return "'" + String.escape(character) + "' + ";
230 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
231 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
232 * the date format that is not specified will default to the current date value for that part. Time parts can also
233 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
234 * string or the parse operation will fail.
237 //dt = Fri May 25 2007 (current date)
240 //dt = Thu May 25 2006 (today's month/day in 2006)
241 dt = Date.parseDate("2006", "Y");
243 //dt = Sun Jan 15 2006 (all date parts specified)
244 dt = Date.parseDate("2006-1-15", "Y-m-d");
246 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
247 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
249 * @param {String} input The unparsed date as a string
250 * @param {String} format The format the date is in
251 * @return {Date} The parsed date
254 Date.parseDate = function(input, format) {
255 if (Date.parseFunctions[format] == null) {
256 Date.createParser(format);
258 var func = Date.parseFunctions[format];
259 return Date[func](input);
265 Date.createParser = function(format) {
266 var funcName = "parse" + Date.parseFunctions.count++;
267 var regexNum = Date.parseRegexes.length;
268 var currentGroup = 1;
269 Date.parseFunctions[format] = funcName;
271 var code = "Date." + funcName + " = function(input){\n"
272 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
273 + "var d = new Date();\n"
274 + "y = d.getFullYear();\n"
275 + "m = d.getMonth();\n"
276 + "d = d.getDate();\n"
277 + "if (typeof(input) !== 'string') { input = input.toString(); }\n"
278 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
279 + "if (results && results.length > 0) {";
284 for (var i = 0; i < format.length; ++i) {
285 ch = format.charAt(i);
286 if (!special && ch == "\\") {
291 regex += String.escape(ch);
294 var obj = Date.formatCodeToRegex(ch, currentGroup);
295 currentGroup += obj.g;
297 if (obj.g && obj.c) {
303 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
304 + "{v = new Date(y, m, d, h, i, s);}\n"
305 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
306 + "{v = new Date(y, m, d, h, i);}\n"
307 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
308 + "{v = new Date(y, m, d, h);}\n"
309 + "else if (y >= 0 && m >= 0 && d > 0)\n"
310 + "{v = new Date(y, m, d);}\n"
311 + "else if (y >= 0 && m >= 0)\n"
312 + "{v = new Date(y, m);}\n"
313 + "else if (y >= 0)\n"
314 + "{v = new Date(y);}\n"
315 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
316 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
317 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
320 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
321 /** eval:var:zzzzzzzzzzzzz */
326 Date.formatCodeToRegex = function(character, currentGroup) {
331 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
334 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
335 s:"(\\d{1,2})"}; // day of month without leading zeroes
338 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
339 s:"(\\d{2})"}; // day of month with leading zeroes
343 s:"(?:" + Date.dayNames.join("|") + ")"};
347 s:"(?:st|nd|rd|th)"};
362 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
363 s:"(" + Date.monthNames.join("|") + ")"};
366 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
367 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
370 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
371 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
374 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
375 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
386 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
390 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
391 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
395 c:"if (results[" + currentGroup + "] == 'am') {\n"
396 + "if (h == 12) { h = 0; }\n"
397 + "} else { if (h < 12) { h += 12; }}",
401 c:"if (results[" + currentGroup + "] == 'AM') {\n"
402 + "if (h == 12) { h = 0; }\n"
403 + "} else { if (h < 12) { h += 12; }}",
408 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
409 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
413 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
414 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
417 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
421 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
426 "o = results[", currentGroup, "];\n",
427 "var sn = o.substring(0,1);\n", // get + / - sign
428 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
429 "var mn = o.substring(3,5) % 60;\n", // get minutes
430 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
431 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
433 s:"([+\-]\\d{2,4})"};
439 "o = results[", currentGroup, "];\n",
440 "var sn = o.substring(0,1);\n",
441 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
442 "var mn = o.substring(4,6) % 60;\n",
443 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
444 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
450 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
453 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
454 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
455 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
459 s:String.escape(character)};
464 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
465 * @return {String} The abbreviated timezone name (e.g. 'CST')
467 Date.prototype.getTimezone = function() {
468 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
472 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
473 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
475 Date.prototype.getGMTOffset = function() {
476 return (this.getTimezoneOffset() > 0 ? "-" : "+")
477 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
478 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
482 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
483 * @return {String} 2-characters representing hours and 2-characters representing minutes
484 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
486 Date.prototype.getGMTColonOffset = function() {
487 return (this.getTimezoneOffset() > 0 ? "-" : "+")
488 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
490 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
494 * Get the numeric day number of the year, adjusted for leap year.
495 * @return {Number} 0 through 364 (365 in leap years)
497 Date.prototype.getDayOfYear = function() {
499 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
500 for (var i = 0; i < this.getMonth(); ++i) {
501 num += Date.daysInMonth[i];
503 return num + this.getDate() - 1;
507 * Get the string representation of the numeric week number of the year
508 * (equivalent to the format specifier 'W').
509 * @return {String} '00' through '52'
511 Date.prototype.getWeekOfYear = function() {
512 // Skip to Thursday of this week
513 var now = this.getDayOfYear() + (4 - this.getDay());
514 // Find the first Thursday of the year
515 var jan1 = new Date(this.getFullYear(), 0, 1);
516 var then = (7 - jan1.getDay() + 4);
517 return String.leftPad(((now - then) / 7) + 1, 2, "0");
521 * Whether or not the current date is in a leap year.
522 * @return {Boolean} True if the current date is in a leap year, else false
524 Date.prototype.isLeapYear = function() {
525 var year = this.getFullYear();
526 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
530 * Get the first day of the current month, adjusted for leap year. The returned value
531 * is the numeric day index within the week (0-6) which can be used in conjunction with
532 * the {@link #monthNames} array to retrieve the textual day name.
535 var dt = new Date('1/10/2007');
536 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
538 * @return {Number} The day number (0-6)
540 Date.prototype.getFirstDayOfMonth = function() {
541 var day = (this.getDay() - (this.getDate() - 1)) % 7;
542 return (day < 0) ? (day + 7) : day;
546 * Get the last day of the current month, adjusted for leap year. The returned value
547 * is the numeric day index within the week (0-6) which can be used in conjunction with
548 * the {@link #monthNames} array to retrieve the textual day name.
551 var dt = new Date('1/10/2007');
552 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
554 * @return {Number} The day number (0-6)
556 Date.prototype.getLastDayOfMonth = function() {
557 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
558 return (day < 0) ? (day + 7) : day;
563 * Get the first date of this date's month
566 Date.prototype.getFirstDateOfMonth = function() {
567 return new Date(this.getFullYear(), this.getMonth(), 1);
571 * Get the last date of this date's month
574 Date.prototype.getLastDateOfMonth = function() {
575 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
578 * Get the number of days in the current month, adjusted for leap year.
579 * @return {Number} The number of days in the month
581 Date.prototype.getDaysInMonth = function() {
582 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
583 return Date.daysInMonth[this.getMonth()];
587 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
588 * @return {String} 'st, 'nd', 'rd' or 'th'
590 Date.prototype.getSuffix = function() {
591 switch (this.getDate()) {
608 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
611 * An array of textual month names.
612 * Override these values for international dates, for example...
613 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
632 * An array of textual day names.
633 * Override these values for international dates, for example...
634 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
650 Date.monthNumbers = {
665 * Creates and returns a new Date instance with the exact same date value as the called instance.
666 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
667 * variable will also be changed. When the intention is to create a new variable that will not
668 * modify the original instance, you should create a clone.
670 * Example of correctly cloning a date:
673 var orig = new Date('10/1/2006');
676 document.write(orig); //returns 'Thu Oct 05 2006'!
679 var orig = new Date('10/1/2006');
680 var copy = orig.clone();
682 document.write(orig); //returns 'Thu Oct 01 2006'
684 * @return {Date} The new Date instance
686 Date.prototype.clone = function() {
687 return new Date(this.getTime());
691 * Clears any time information from this date
692 @param {Boolean} clone true to create a clone of this date, clear the time and return it
693 @return {Date} this or the clone
695 Date.prototype.clearTime = function(clone){
697 return this.clone().clearTime();
702 this.setMilliseconds(0);
707 // safari setMonth is broken -- check that this is only donw once...
708 if(Roo.isSafari && typeof(Date.brokenSetMonth) == 'undefined'){
709 Date.brokenSetMonth = Date.prototype.setMonth;
710 Date.prototype.setMonth = function(num){
712 var n = Math.ceil(-num);
713 var back_year = Math.ceil(n/12);
714 var month = (n % 12) ? 12 - n % 12 : 0 ;
715 this.setFullYear(this.getFullYear() - back_year);
716 return Date.brokenSetMonth.call(this, month);
718 return Date.brokenSetMonth.apply(this, arguments);
723 /** Date interval constant
727 /** Date interval constant
731 /** Date interval constant
735 /** Date interval constant
739 /** Date interval constant
743 /** Date interval constant
747 /** Date interval constant
753 * Provides a convenient method of performing basic date arithmetic. This method
754 * does not modify the Date instance being called - it creates and returns
755 * a new Date instance containing the resulting date value.
760 var dt = new Date('10/29/2006').add(Date.DAY, 5);
761 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
763 //Negative values will subtract correctly:
764 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
765 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
767 //You can even chain several calls together in one line!
768 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
769 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
772 * @param {String} interval A valid date interval enum value
773 * @param {Number} value The amount to add to the current date
774 * @return {Date} The new Date instance
776 Date.prototype.add = function(interval, value){
777 var d = this.clone();
778 if (!interval || value === 0) { return d; }
779 switch(interval.toLowerCase()){
781 d.setMilliseconds(this.getMilliseconds() + value);
784 d.setSeconds(this.getSeconds() + value);
787 d.setMinutes(this.getMinutes() + value);
790 d.setHours(this.getHours() + value);
793 d.setDate(this.getDate() + value);
796 var day = this.getDate();
798 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
801 d.setMonth(this.getMonth() + value);
804 d.setFullYear(this.getFullYear() + value);