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 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};
125 Date.escape = function(string) {
126 return string.replace(/('|\\)/g, "\\$1");
130 Date.leftPad = function (val, size, ch) {
131 var result = new String(val);
132 if(ch === null || ch === undefined || ch === '') {
135 while (result.length < size) {
136 result = ch + result;
152 Date.prototype.dateFormat = function(format) {
153 if (Date.formatFunctions[format] == null) {
154 Date.createNewFormat(format);
156 var func = Date.formatFunctions[format];
162 * Formats a date given the supplied format string
163 * @param {String} format The format string
164 * @return {String} The formatted date
167 Date.prototype.format = Date.prototype.dateFormat;
170 Date.createNewFormat = function(format) {
171 var funcName = "format" + Date.formatFunctions.count++;
172 Date.formatFunctions[format] = funcName;
173 var code = "Date.prototype." + funcName + " = function(){return ";
176 for (var i = 0; i < format.length; ++i) {
177 ch = format.charAt(i);
178 if (!special && ch == "\\") {
183 code += "'" + Date.escape(ch) + "' + ";
186 code += Date.getFormatCode(ch);
189 /** eval:var:zzzzzzzzzzzzz */
190 eval(code.substring(0, code.length - 3) + ";}");
194 Date.getFormatCode = function(character) {
197 return "Date.leftPad(this.getDate(), 2, '0') + ";
199 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
201 return "this.getDate() + ";
203 return "Date.dayNames[this.getDay()] + ";
205 return "this.getSuffix() + ";
207 return "this.getDay() + ";
209 return "this.getDayOfYear() + ";
211 return "this.getWeekOfYear() + ";
213 return "Date.monthNames[this.getMonth()] + ";
215 return "Date.leftPad(this.getMonth() + 1, 2, '0') + ";
217 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
219 return "(this.getMonth() + 1) + ";
221 return "this.getDaysInMonth() + ";
223 return "(this.isLeapYear() ? 1 : 0) + ";
225 return "this.getFullYear() + ";
227 return "('' + this.getFullYear()).substring(2, 4) + ";
229 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
231 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
233 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
235 return "this.getHours() + ";
237 return "Date.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
239 return "Date.leftPad(this.getHours(), 2, '0') + ";
241 return "Date.leftPad(this.getMinutes(), 2, '0') + ";
243 return "Date.leftPad(this.getSeconds(), 2, '0') + ";
245 return "this.getGMTOffset() + ";
247 return "this.getGMTColonOffset() + ";
249 return "this.getTimezone() + ";
251 return "(this.getTimezoneOffset() * -60) + ";
253 return "'" + Date.escape(character) + "' + ";
258 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
259 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
260 * the date format that is not specified will default to the current date value for that part. Time parts can also
261 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
262 * string or the parse operation will fail.
265 //dt = Fri May 25 2007 (current date)
268 //dt = Thu May 25 2006 (today's month/day in 2006)
269 dt = Date.parseDate("2006", "Y");
271 //dt = Sun Jan 15 2006 (all date parts specified)
272 dt = Date.parseDate("2006-1-15", "Y-m-d");
274 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
275 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
277 * @param {String} input The unparsed date as a string
278 * @param {String} format The format the date is in
279 * @return {Date} The parsed date
282 Date.parseDate = function(input, format) {
283 if (Date.parseFunctions[format] == null) {
284 Date.createParser(format);
286 var func = Date.parseFunctions[format];
287 return Date[func](input);
292 Date.createParser = function(format) {
293 var funcName = "parse" + Date.parseFunctions.count++;
294 var regexNum = Date.parseRegexes.length;
295 var currentGroup = 1;
296 Date.parseFunctions[format] = funcName;
298 var code = "Date." + funcName + " = function(input){\n"
299 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
300 + "var d = new Date();\n"
301 + "y = d.getFullYear();\n"
302 + "m = d.getMonth();\n"
303 + "d = d.getDate();\n"
304 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
305 + "if (results && results.length > 0) {";
310 for (var i = 0; i < format.length; ++i) {
311 ch = format.charAt(i);
312 if (!special && ch == "\\") {
317 regex += Date.escape(ch);
320 var obj = Date.formatCodeToRegex(ch, currentGroup);
321 currentGroup += obj.g;
323 if (obj.g && obj.c) {
329 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
330 + "{v = new Date(y, m, d, h, i, s);}\n"
331 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
332 + "{v = new Date(y, m, d, h, i);}\n"
333 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
334 + "{v = new Date(y, m, d, h);}\n"
335 + "else if (y >= 0 && m >= 0 && d > 0)\n"
336 + "{v = new Date(y, m, d);}\n"
337 + "else if (y >= 0 && m >= 0)\n"
338 + "{v = new Date(y, m);}\n"
339 + "else if (y >= 0)\n"
340 + "{v = new Date(y);}\n"
341 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
342 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
343 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
346 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
347 /** eval:var:zzzzzzzzzzzzz */
352 Date.formatCodeToRegex = function(character, currentGroup) {
357 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
360 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
361 s:"(\\d{1,2})"}; // day of month without leading zeroes
364 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
365 s:"(\\d{2})"}; // day of month with leading zeroes
369 s:"(?:" + Date.dayNames.join("|") + ")"};
373 s:"(?:st|nd|rd|th)"};
388 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
389 s:"(" + Date.monthNames.join("|") + ")"};
392 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
393 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
396 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
397 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
400 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
401 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
412 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
416 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
417 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
421 c:"if (results[" + currentGroup + "] == 'am') {\n"
422 + "if (h == 12) { h = 0; }\n"
423 + "} else { if (h < 12) { h += 12; }}",
427 c:"if (results[" + currentGroup + "] == 'AM') {\n"
428 + "if (h == 12) { h = 0; }\n"
429 + "} else { if (h < 12) { h += 12; }}",
434 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
435 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
439 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
440 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
443 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
447 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
452 "o = results[", currentGroup, "];\n",
453 "var sn = o.substring(0,1);\n", // get + / - sign
454 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
455 "var mn = o.substring(3,5) % 60;\n", // get minutes
456 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
457 " (sn + Date.leftPad(hr, 2, 0) + Date.leftPad(mn, 2, 0)) : null;\n"
463 "o = results[", currentGroup, "];\n",
464 "var sn = o.substring(0,1);\n",
465 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
466 "var mn = o.substring(4,6) % 60;\n",
467 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
468 " (sn + Date.leftPad(hr, 2, 0) + Date.leftPad(mn, 2, 0)) : null;\n"
474 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
477 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
478 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
479 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
483 s:Date.escape(character)};
488 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
489 * @return {String} The abbreviated timezone name (e.g. 'CST')
491 Date.prototype.getTimezone = function() {
492 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
496 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
497 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
499 Date.prototype.getGMTOffset = function() {
500 return (this.getTimezoneOffset() > 0 ? "-" : "+")
501 + Date.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
502 + Date.leftPad(this.getTimezoneOffset() % 60, 2, "0");
506 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
507 * @return {String} 2-characters representing hours and 2-characters representing minutes
508 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
510 Date.prototype.getGMTColonOffset = function() {
511 return (this.getTimezoneOffset() > 0 ? "-" : "+")
512 + Date.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
514 + Date.leftPad(this.getTimezoneOffset() %60, 2, "0");
518 * Get the numeric day number of the year, adjusted for leap year.
519 * @return {Number} 0 through 364 (365 in leap years)
521 Date.prototype.getDayOfYear = function() {
523 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
524 for (var i = 0; i < this.getMonth(); ++i) {
525 num += Date.daysInMonth[i];
527 return num + this.getDate() - 1;
531 * Get the string representation of the numeric week number of the year
532 * (equivalent to the format specifier 'W').
533 * @return {String} '00' through '52'
535 Date.prototype.getWeekOfYear = function() {
536 // Skip to Thursday of this week
537 var now = this.getDayOfYear() + (4 - this.getDay());
538 // Find the first Thursday of the year
539 var jan1 = new Date(this.getFullYear(), 0, 1);
540 var then = (7 - jan1.getDay() + 4);
541 return Date.leftPad(((now - then) / 7) + 1, 2, "0");
545 * Whether or not the current date is in a leap year.
546 * @return {Boolean} True if the current date is in a leap year, else false
548 Date.prototype.isLeapYear = function() {
549 var year = this.getFullYear();
550 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
554 * Get the first day of the current month, adjusted for leap year. The returned value
555 * is the numeric day index within the week (0-6) which can be used in conjunction with
556 * the {@link #monthNames} array to retrieve the textual day name.
559 var dt = new Date('1/10/2007');
560 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
562 * @return {Number} The day number (0-6)
564 Date.prototype.getFirstDayOfMonth = function() {
565 var day = (this.getDay() - (this.getDate() - 1)) % 7;
566 return (day < 0) ? (day + 7) : day;
570 * Get the last day of the current month, adjusted for leap year. The returned value
571 * is the numeric day index within the week (0-6) which can be used in conjunction with
572 * the {@link #monthNames} array to retrieve the textual day name.
575 var dt = new Date('1/10/2007');
576 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
578 * @return {Number} The day number (0-6)
580 Date.prototype.getLastDayOfMonth = function() {
581 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
582 return (day < 0) ? (day + 7) : day;
587 * Get the first date of this date's month
590 Date.prototype.getFirstDateOfMonth = function() {
591 return new Date(this.getFullYear(), this.getMonth(), 1);
595 * Get the last date of this date's month
598 Date.prototype.getLastDateOfMonth = function() {
599 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
602 * Get the number of days in the current month, adjusted for leap year.
603 * @return {Number} The number of days in the month
605 Date.prototype.getDaysInMonth = function() {
606 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
607 return Date.daysInMonth[this.getMonth()];
611 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
612 * @return {String} 'st, 'nd', 'rd' or 'th'
614 Date.prototype.getSuffix = function() {
615 switch (this.getDate()) {
632 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
635 * An array of textual month names.
636 * Override these values for international dates, for example...
637 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
656 * An array of textual day names.
657 * Override these values for international dates, for example...
658 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
674 Date.monthNumbers = {
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
710 Date.prototype.clone = function() {
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 Date.prototype.clearTime = function(clone){
721 return this.clone().clearTime();
726 this.setMilliseconds(0);
731 // safari setMonth is broken
734 Date.brokenSetMonth = Date.prototype.setMonth;
735 Date.prototype.setMonth = function(num){
737 var n = Math.ceil(-num);
738 var back_year = Math.ceil(n/12);
739 var month = (n % 12) ? 12 - n % 12 : 0 ;
740 this.setFullYear(this.getFullYear() - back_year);
741 return Date.brokenSetMonth.call(this, month);
743 return Date.brokenSetMonth.apply(this, arguments);
749 /** Date interval constant
753 /** Date interval constant
757 /** Date interval constant
761 /** Date interval constant
765 /** Date interval constant
769 /** Date interval constant
773 /** Date interval constant
779 * Provides a convenient method of performing basic date arithmetic. This method
780 * does not modify the Date instance being called - it creates and returns
781 * a new Date instance containing the resulting date value.
786 var dt = new Date('10/29/2006').add(Date.DAY, 5);
787 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
789 //Negative values will subtract correctly:
790 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
791 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
793 //You can even chain several calls together in one line!
794 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
795 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
798 * @param {String} interval A valid date interval enum value
799 * @param {Number} value The amount to add to the current date
800 * @return {Date} The new Date instance
802 Date.prototype.add = function(interval, value){
803 var d = this.clone();
804 if (!interval || value === 0) return d;
805 switch(interval.toLowerCase()){
807 d.setMilliseconds(this.getMilliseconds() + value);
810 d.setSeconds(this.getSeconds() + value);
813 d.setMinutes(this.getMinutes() + value);
816 d.setHours(this.getHours() + value);
819 d.setDate(this.getDate() + value);
822 var day = this.getDate();
824 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
827 d.setMonth(this.getMonth() + value);
830 d.setFullYear(this.getFullYear() + value);