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
51 T CST Timezone setting of the machine running the code
52 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
55 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
57 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
58 document.write(dt.format('Y-m-d')); //2007-01-10
59 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
60 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
63 * Here are some standard date/time patterns that you might find helpful. They
64 * are not part of the source of Date.js, but to use them you can simply copy this
65 * block of code into any script that is included after Date.js and they will also become
66 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
69 ISO8601Long:"Y-m-d H:i:s",
72 LongDate: "l, F d, Y",
73 FullDateTime: "l, F d, Y g:i:s A",
77 SortableDateTime: "Y-m-d\\TH:i:s",
78 UniversalSortableDateTime: "Y-m-d H:i:sO",
86 document.write(dt.format(Date.patterns.ShortDate));
91 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
92 * They generate precompiled functions from date formats instead of parsing and
93 * processing the pattern every time you format a date. These functions are available
94 * on every Date object (any javascript function).
96 * The original article and download are here:
97 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
104 Returns the number of milliseconds between this date and date
105 @param {Date} date (optional) Defaults to now
106 @return {Number} The diff in milliseconds
107 @member Date getElapsed
109 Date.prototype.getElapsed = function(date) {
110 return Math.abs((date || new Date()).getTime()-this.getTime());
112 // was in date file..
116 Date.parseFunctions = {count:0};
118 Date.parseRegexes = [];
120 Date.formatFunctions = {count:0};
123 Date.prototype.dateFormat = function(format) {
124 if (Date.formatFunctions[format] == null) {
125 Date.createNewFormat(format);
127 var func = Date.formatFunctions[format];
133 * Formats a date given the supplied format string
134 * @param {String} format The format string
135 * @return {String} The formatted date
138 Date.prototype.format = Date.prototype.dateFormat;
141 Date.createNewFormat = function(format) {
142 var funcName = "format" + Date.formatFunctions.count++;
143 Date.formatFunctions[format] = funcName;
144 var code = "Date.prototype." + funcName + " = function(){return ";
147 for (var i = 0; i < format.length; ++i) {
148 ch = format.charAt(i);
149 if (!special && ch == "\\") {
154 code += "'" + String.escape(ch) + "' + ";
157 code += Date.getFormatCode(ch);
160 /** eval:var:zzzzzzzzzzzzz */
161 eval(code.substring(0, code.length - 3) + ";}");
165 Date.getFormatCode = function(character) {
168 return "String.leftPad(this.getDate(), 2, '0') + ";
170 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
172 return "this.getDate() + ";
174 return "Date.dayNames[this.getDay()] + ";
176 return "this.getSuffix() + ";
178 return "this.getDay() + ";
180 return "this.getDayOfYear() + ";
182 return "this.getWeekOfYear() + ";
184 return "Date.monthNames[this.getMonth()] + ";
186 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
188 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
190 return "(this.getMonth() + 1) + ";
192 return "this.getDaysInMonth() + ";
194 return "(this.isLeapYear() ? 1 : 0) + ";
196 return "this.getFullYear() + ";
198 return "('' + this.getFullYear()).substring(2, 4) + ";
200 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
202 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
204 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
206 return "this.getHours() + ";
208 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
210 return "String.leftPad(this.getHours(), 2, '0') + ";
212 return "String.leftPad(this.getMinutes(), 2, '0') + ";
214 return "String.leftPad(this.getSeconds(), 2, '0') + ";
216 return "this.getGMTOffset() + ";
218 return "this.getTimezone() + ";
220 return "(this.getTimezoneOffset() * -60) + ";
222 return "'" + String.escape(character) + "' + ";
227 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
228 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
229 * the date format that is not specified will default to the current date value for that part. Time parts can also
230 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
231 * string or the parse operation will fail.
234 //dt = Fri May 25 2007 (current date)
237 //dt = Thu May 25 2006 (today's month/day in 2006)
238 dt = Date.parseDate("2006", "Y");
240 //dt = Sun Jan 15 2006 (all date parts specified)
241 dt = Date.parseDate("2006-1-15", "Y-m-d");
243 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
244 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
246 * @param {String} input The unparsed date as a string
247 * @param {String} format The format the date is in
248 * @return {Date} The parsed date
251 Date.parseDate = function(input, format) {
252 if (Date.parseFunctions[format] == null) {
253 Date.createParser(format);
255 var func = Date.parseFunctions[format];
256 return Date[func](input);
260 Date.createParser = function(format) {
261 var funcName = "parse" + Date.parseFunctions.count++;
262 var regexNum = Date.parseRegexes.length;
263 var currentGroup = 1;
264 Date.parseFunctions[format] = funcName;
266 var code = "Date." + funcName + " = function(input){\n"
267 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
268 + "var d = new Date();\n"
269 + "y = d.getFullYear();\n"
270 + "m = d.getMonth();\n"
271 + "d = d.getDate();\n"
272 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
273 + "if (results && results.length > 0) {";
278 for (var i = 0; i < format.length; ++i) {
279 ch = format.charAt(i);
280 if (!special && ch == "\\") {
285 regex += String.escape(ch);
288 var obj = Date.formatCodeToRegex(ch, currentGroup);
289 currentGroup += obj.g;
291 if (obj.g && obj.c) {
297 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
298 + "{v = new Date(y, m, d, h, i, s);}\n"
299 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
300 + "{v = new Date(y, m, d, h, i);}\n"
301 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
302 + "{v = new Date(y, m, d, h);}\n"
303 + "else if (y >= 0 && m >= 0 && d > 0)\n"
304 + "{v = new Date(y, m, d);}\n"
305 + "else if (y >= 0 && m >= 0)\n"
306 + "{v = new Date(y, m);}\n"
307 + "else if (y >= 0)\n"
308 + "{v = new Date(y);}\n"
309 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
310 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
311 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
314 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
315 /** eval:var:zzzzzzzzzzzzz */
320 Date.formatCodeToRegex = function(character, currentGroup) {
325 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
328 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
329 s:"(\\d{1,2})"}; // day of month without leading zeroes
332 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
333 s:"(\\d{2})"}; // day of month with leading zeroes
337 s:"(?:" + Date.dayNames.join("|") + ")"};
341 s:"(?:st|nd|rd|th)"};
356 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
357 s:"(" + Date.monthNames.join("|") + ")"};
360 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
361 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
364 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
365 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
368 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
369 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
380 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
384 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
385 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
389 c:"if (results[" + currentGroup + "] == 'am') {\n"
390 + "if (h == 12) { h = 0; }\n"
391 + "} else { if (h < 12) { h += 12; }}",
395 c:"if (results[" + currentGroup + "] == 'AM') {\n"
396 + "if (h == 12) { h = 0; }\n"
397 + "} else { if (h < 12) { h += 12; }}",
402 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
403 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
407 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
408 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
411 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
415 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
420 "o = results[", currentGroup, "];\n",
421 "var sn = o.substring(0,1);\n", // get + / - sign
422 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
423 "var mn = o.substring(3,5) % 60;\n", // get minutes
424 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
425 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
431 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
434 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
435 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
436 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
440 s:String.escape(character)};
445 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
446 * @return {String} The abbreviated timezone name (e.g. 'CST')
448 Date.prototype.getTimezone = function() {
449 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
453 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
454 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
456 Date.prototype.getGMTOffset = function() {
457 return (this.getTimezoneOffset() > 0 ? "-" : "+")
458 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
459 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
463 * Get the numeric day number of the year, adjusted for leap year.
464 * @return {Number} 0 through 364 (365 in leap years)
466 Date.prototype.getDayOfYear = function() {
468 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
469 for (var i = 0; i < this.getMonth(); ++i) {
470 num += Date.daysInMonth[i];
472 return num + this.getDate() - 1;
476 * Get the string representation of the numeric week number of the year
477 * (equivalent to the format specifier 'W').
478 * @return {String} '00' through '52'
480 Date.prototype.getWeekOfYear = function() {
481 // Skip to Thursday of this week
482 var now = this.getDayOfYear() + (4 - this.getDay());
483 // Find the first Thursday of the year
484 var jan1 = new Date(this.getFullYear(), 0, 1);
485 var then = (7 - jan1.getDay() + 4);
486 return String.leftPad(((now - then) / 7) + 1, 2, "0");
490 * Whether or not the current date is in a leap year.
491 * @return {Boolean} True if the current date is in a leap year, else false
493 Date.prototype.isLeapYear = function() {
494 var year = this.getFullYear();
495 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
499 * Get the first day of the current month, adjusted for leap year. The returned value
500 * is the numeric day index within the week (0-6) which can be used in conjunction with
501 * the {@link #monthNames} array to retrieve the textual day name.
504 var dt = new Date('1/10/2007');
505 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
507 * @return {Number} The day number (0-6)
509 Date.prototype.getFirstDayOfMonth = function() {
510 var day = (this.getDay() - (this.getDate() - 1)) % 7;
511 return (day < 0) ? (day + 7) : day;
515 * Get the last day of the current month, adjusted for leap year. The returned value
516 * is the numeric day index within the week (0-6) which can be used in conjunction with
517 * the {@link #monthNames} array to retrieve the textual day name.
520 var dt = new Date('1/10/2007');
521 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
523 * @return {Number} The day number (0-6)
525 Date.prototype.getLastDayOfMonth = function() {
526 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
527 return (day < 0) ? (day + 7) : day;
532 * Get the first date of this date's month
535 Date.prototype.getFirstDateOfMonth = function() {
536 return new Date(this.getFullYear(), this.getMonth(), 1);
540 * Get the last date of this date's month
543 Date.prototype.getLastDateOfMonth = function() {
544 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
547 * Get the number of days in the current month, adjusted for leap year.
548 * @return {Number} The number of days in the month
550 Date.prototype.getDaysInMonth = function() {
551 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
552 return Date.daysInMonth[this.getMonth()];
556 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
557 * @return {String} 'st, 'nd', 'rd' or 'th'
559 Date.prototype.getSuffix = function() {
560 switch (this.getDate()) {
577 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
580 * An array of textual month names.
581 * Override these values for international dates, for example...
582 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
601 * An array of textual day names.
602 * Override these values for international dates, for example...
603 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
619 Date.monthNumbers = {
634 * Creates and returns a new Date instance with the exact same date value as the called instance.
635 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
636 * variable will also be changed. When the intention is to create a new variable that will not
637 * modify the original instance, you should create a clone.
639 * Example of correctly cloning a date:
642 var orig = new Date('10/1/2006');
645 document.write(orig); //returns 'Thu Oct 05 2006'!
648 var orig = new Date('10/1/2006');
649 var copy = orig.clone();
651 document.write(orig); //returns 'Thu Oct 01 2006'
653 * @return {Date} The new Date instance
655 Date.prototype.clone = function() {
656 return new Date(this.getTime());
660 * Clears any time information from this date
661 @param {Boolean} clone true to create a clone of this date, clear the time and return it
662 @return {Date} this or the clone
664 Date.prototype.clearTime = function(clone){
666 return this.clone().clearTime();
671 this.setMilliseconds(0);
676 // safari setMonth is broken
678 Date.brokenSetMonth = Date.prototype.setMonth;
679 Date.prototype.setMonth = function(num){
681 var n = Math.ceil(-num);
682 var back_year = Math.ceil(n/12);
683 var month = (n % 12) ? 12 - n % 12 : 0 ;
684 this.setFullYear(this.getFullYear() - back_year);
685 return Date.brokenSetMonth.call(this, month);
687 return Date.brokenSetMonth.apply(this, arguments);
692 /** Date interval constant
696 /** Date interval constant
700 /** Date interval constant
704 /** Date interval constant
708 /** Date interval constant
712 /** Date interval constant
716 /** Date interval constant
722 * Provides a convenient method of performing basic date arithmetic. This method
723 * does not modify the Date instance being called - it creates and returns
724 * a new Date instance containing the resulting date value.
729 var dt = new Date('10/29/2006').add(Date.DAY, 5);
730 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
732 //Negative values will subtract correctly:
733 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
734 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
736 //You can even chain several calls together in one line!
737 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
738 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
741 * @param {String} interval A valid date interval enum value
742 * @param {Number} value The amount to add to the current date
743 * @return {Date} The new Date instance
745 Date.prototype.add = function(interval, value){
746 var d = this.clone();
747 if (!interval || value === 0) return d;
748 switch(interval.toLowerCase()){
750 d.setMilliseconds(this.getMilliseconds() + value);
753 d.setSeconds(this.getSeconds() + value);
756 d.setMinutes(this.getMinutes() + value);
759 d.setHours(this.getHours() + value);
762 d.setDate(this.getDate() + value);
765 var day = this.getDate();
767 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
770 d.setMonth(this.getMonth() + value);
773 d.setFullYear(this.getFullYear() + value);