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">
12 //imports['Date.js'].load(Date);
14 imports['String.js'].load(String);
19 load = false; // declare global for gnome langs.
28 * The date parsing and format syntax is a subset of
29 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
30 * supported will provide results equivalent to their PHP versions.
32 * Following is the list of all currently supported formats:
35 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
37 Format Output Description
38 ------ ---------- --------------------------------------------------------------
39 d 10 Day of the month, 2 digits with leading zeros
40 D Wed A textual representation of a day, three letters
41 j 10 Day of the month without leading zeros
42 l Wednesday A full textual representation of the day of the week
43 S th English ordinal day of month suffix, 2 chars (use with j)
44 w 3 Numeric representation of the day of the week
45 z 9 The julian date, or day of the year (0-365)
46 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
47 F January A full textual representation of the month
48 m 01 Numeric representation of a month, with leading zeros
49 M Jan Month name abbreviation, three letters
50 n 1 Numeric representation of a month, without leading zeros
51 t 31 Number of days in the given month
52 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
53 Y 2007 A full numeric representation of a year, 4 digits
54 y 07 A two digit representation of a year
55 a pm Lowercase Ante meridiem and Post meridiem
56 A PM Uppercase Ante meridiem and Post meridiem
57 g 3 12-hour format of an hour without leading zeros
58 G 15 24-hour format of an hour without leading zeros
59 h 03 12-hour format of an hour with leading zeros
60 H 15 24-hour format of an hour with leading zeros
61 i 05 Minutes with leading zeros
62 s 01 Seconds, with leading zeros
63 O -0600 Difference to Greenwich time (GMT) in hours
64 T CST Timezone setting of the machine running the code
65 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
68 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
70 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
71 document.write(dt.format('Y-m-d')); //2007-01-10
72 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
73 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
76 * Here are some standard date/time patterns that you might find helpful. They
77 * are not part of the source of Date.js, but to use them you can simply copy this
78 * block of code into any script that is included after Date.js and they will also become
79 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
82 ISO8601Long:"Y-m-d H:i:s",
85 LongDate: "l, F d, Y",
86 FullDateTime: "l, F d, Y g:i:s A",
90 SortableDateTime: "Y-m-d\\TH:i:s",
91 UniversalSortableDateTime: "Y-m-d H:i:sO",
99 document.write(dt.format(Date.patterns.ShortDate));
104 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
105 * They generate precompiled functions from date formats instead of parsing and
106 * processing the pattern every time you format a date. These functions are available
107 * on every Date object (any javascript function).
109 * The original article and download are here:
110 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
117 Returns the number of milliseconds between this date and date
118 @param {Date} date (optional) Defaults to now
119 @return {Number} The diff in milliseconds
120 @member Date getElapsed
125 parseFunctions : {count:0},
129 formatFunctions : {count:0},
133 // safari setMonth is broken
135 /** Date interval constant
139 /** Date interval constant
143 /** Date interval constant
147 /** Date interval constant
151 /** Date interval constant
155 /** Date interval constant
159 /** Date interval constant
165 daysInMonth : [31,28,31,30,31,30,31,31,30,31,30,31],
168 * An array of textual month names.
169 * Override these values for international dates, for example...
170 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
189 * An array of textual day names.
190 * Override these values for international dates, for example...
191 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
221 createNewFormat : function(format) {
222 var funcName = "format" + Date.formatFunctions.count++;
223 Date.formatFunctions[format] = funcName;
224 var code = "Date.prototype." + funcName + " = function(){return ";
227 for (var i = 0; i < format.length; ++i) {
228 ch = format.charAt(i);
229 if (!special && ch == "\\") {
234 code += "'" + String.escape(ch) + "' + ";
237 code += Date.getFormatCode(ch);
240 /** eval:var:zzzzzzzzzzzzz */
241 eval(code.substring(0, code.length - 3) + ";}");
245 getFormatCode : function(character) {
248 return "String.leftPad(this.getDate(), 2, '0') + ";
250 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
252 return "this.getDate() + ";
254 return "Date.dayNames[this.getDay()] + ";
256 return "this.getSuffix() + ";
258 return "this.getDay() + ";
260 return "this.getDayOfYear() + ";
262 return "this.getWeekOfYear() + ";
264 return "Date.monthNames[this.getMonth()] + ";
266 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
268 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
270 return "(this.getMonth() + 1) + ";
272 return "this.getDaysInMonth() + ";
274 return "(this.isLeapYear() ? 1 : 0) + ";
276 return "this.getFullYear() + ";
278 return "('' + this.getFullYear()).substring(2, 4) + ";
280 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
282 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
284 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
286 return "this.getHours() + ";
288 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
290 return "String.leftPad(this.getHours(), 2, '0') + ";
292 return "String.leftPad(this.getMinutes(), 2, '0') + ";
294 return "String.leftPad(this.getSeconds(), 2, '0') + ";
296 return "this.getGMTOffset() + ";
298 return "this.getTimezone() + ";
300 return "(this.getTimezoneOffset() * -60) + ";
302 return "'" + String.escape(character) + "' + ";
307 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
308 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
309 * the date format that is not specified will default to the current date value for that part. Time parts can also
310 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
311 * string or the parse operation will fail.
314 //dt = Fri May 25 2007 (current date)
317 //dt = Thu May 25 2006 (today's month/day in 2006)
318 dt = Date.parseDate("2006", "Y");
320 //dt = Sun Jan 15 2006 (all date parts specified)
321 dt = Date.parseDate("2006-1-15", "Y-m-d");
323 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
324 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
326 * @param {String} input The unparsed date as a string
327 * @param {String} format The format the date is in
328 * @return {Date} The parsed date
331 parseDate : function(input, format) {
332 if (Date.parseFunctions[format] == null) {
333 Date.createParser(format);
335 var func = Date.parseFunctions[format];
336 return Date[func](input);
340 createParser : function(format) {
341 var funcName = "parse" + Date.parseFunctions.count++;
342 var regexNum = Date.parseRegexes.length;
343 var currentGroup = 1;
344 Date.parseFunctions[format] = funcName;
346 var code = "Date." + funcName + " = function(input){\n"
347 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
348 + "var d = new Date();\n"
349 + "y = d.getFullYear();\n"
350 + "m = d.getMonth();\n"
351 + "d = d.getDate();\n"
352 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
353 + "if (results && results.length > 0) {";
358 for (var i = 0; i < format.length; ++i) {
359 ch = format.charAt(i);
360 if (!special && ch == "\\") {
365 regex += String.escape(ch);
368 var obj = Date.formatCodeToRegex(ch, currentGroup);
369 currentGroup += obj.g;
371 if (obj.g && obj.c) {
377 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
378 + "{v = new Date(y, m, d, h, i, s);}\n"
379 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
380 + "{v = new Date(y, m, d, h, i);}\n"
381 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
382 + "{v = new Date(y, m, d, h);}\n"
383 + "else if (y >= 0 && m >= 0 && d > 0)\n"
384 + "{v = new Date(y, m, d);}\n"
385 + "else if (y >= 0 && m >= 0)\n"
386 + "{v = new Date(y, m);}\n"
387 + "else if (y >= 0)\n"
388 + "{v = new Date(y);}\n"
389 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
390 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
391 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
394 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
395 /** eval:var:zzzzzzzzzzzzz */
400 formatCodeToRegex : function(character, currentGroup) {
405 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
408 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
409 s:"(\\d{1,2})"}; // day of month without leading zeroes
412 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
413 s:"(\\d{2})"}; // day of month with leading zeroes
417 s:"(?:" + Date.dayNames.join("|") + ")"};
421 s:"(?:st|nd|rd|th)"};
436 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
437 s:"(" + Date.monthNames.join("|") + ")"};
440 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
441 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
444 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
445 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
448 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
449 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
460 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
464 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
465 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
469 c:"if (results[" + currentGroup + "] == 'am') {\n"
470 + "if (h == 12) { h = 0; }\n"
471 + "} else { if (h < 12) { h += 12; }}",
475 c:"if (results[" + currentGroup + "] == 'AM') {\n"
476 + "if (h == 12) { h = 0; }\n"
477 + "} else { if (h < 12) { h += 12; }}",
482 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
483 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
487 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
488 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
491 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
495 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
500 "o = results[", currentGroup, "];\n",
501 "var sn = o.substring(0,1);\n", // get + / - sign
502 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
503 "var mn = o.substring(3,5) % 60;\n", // get minutes
504 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
505 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
511 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
514 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
515 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
516 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
521 s:String.escape(character)};
528 var datePrototype = {
530 getElapsed : function(date) {
531 return Math.abs((date || new Date()).getTime()-this.getTime());
536 * Formats a date given the supplied format string
537 * @param {String} format The format string
538 * @return {String} The formatted date
543 format : function(format) {
544 if (Date.formatFunctions[format] == null) {
545 Date.createNewFormat(format);
547 var func = Date.formatFunctions[format];
551 // private - why is dataFormat an alias?
552 //format : dateFormat;
557 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
558 * @return {String} The abbreviated timezone name (e.g. 'CST')
560 getTimezone : function() {
561 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
565 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
566 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
568 getGMTOffset : function() {
569 return (this.getTimezoneOffset() > 0 ? "-" : "+")
570 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
571 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
575 * Get the numeric day number of the year, adjusted for leap year.
576 * @return {Number} 0 through 364 (365 in leap years)
578 getDayOfYear : function() {
580 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
581 for (var i = 0; i < this.getMonth(); ++i) {
582 num += Date.daysInMonth[i];
584 return num + this.getDate() - 1;
588 * Get the string representation of the numeric week number of the year
589 * (equivalent to the format specifier 'W').
590 * @return {String} '00' through '52'
592 getWeekOfYear : function() {
593 // Skip to Thursday of this week
594 var now = this.getDayOfYear() + (4 - this.getDay());
595 // Find the first Thursday of the year
596 var jan1 = new Date(this.getFullYear(), 0, 1);
597 var then = (7 - jan1.getDay() + 4);
598 return String.leftPad(((now - then) / 7) + 1, 2, "0");
602 * Whether or not the current date is in a leap year.
603 * @return {Boolean} True if the current date is in a leap year, else false
605 isLeapYear : function() {
606 var year = this.getFullYear();
607 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
611 * Get the first day of the current month, adjusted for leap year. The returned value
612 * is the numeric day index within the week (0-6) which can be used in conjunction with
613 * the {@link #monthNames} array to retrieve the textual day name.
616 var dt = new Date('1/10/2007');
617 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
619 * @return {Number} The day number (0-6)
621 getFirstDayOfMonth : function() {
622 var day = (this.getDay() - (this.getDate() - 1)) % 7;
623 return (day < 0) ? (day + 7) : day;
627 * Get the last day of the current month, adjusted for leap year. The returned value
628 * is the numeric day index within the week (0-6) which can be used in conjunction with
629 * the {@link #monthNames} array to retrieve the textual day name.
632 var dt = new Date('1/10/2007');
633 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
635 * @return {Number} The day number (0-6)
637 getLastDayOfMonth : function() {
638 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
639 return (day < 0) ? (day + 7) : day;
644 * Get the first date of this date's month
647 getFirstDateOfMonth : function() {
648 return new Date(this.getFullYear(), this.getMonth(), 1);
652 * Get the last date of this date's month
655 getLastDateOfMonth : function() {
656 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
659 * Get the number of days in the current month, adjusted for leap year.
660 * @return {Number} The number of days in the month
662 getDaysInMonth : function() {
663 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
664 return Date.daysInMonth[this.getMonth()];
668 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
669 * @return {String} 'st, 'nd', 'rd' or 'th'
671 getSuffix : function() {
672 switch (this.getDate()) {
690 * Creates and returns a new Date instance with the exact same date value as the called instance.
691 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
692 * variable will also be changed. When the intention is to create a new variable that will not
693 * modify the original instance, you should create a clone.
695 * Example of correctly cloning a date:
698 var orig = new Date('10/1/2006');
701 document.write(orig); //returns 'Thu Oct 05 2006'!
704 var orig = new Date('10/1/2006');
705 var copy = orig.clone();
707 document.write(orig); //returns 'Thu Oct 01 2006'
709 * @return {Date} The new Date instance
712 return new Date(this.getTime());
716 * Clears any time information from this date
717 @param {Boolean} clone true to create a clone of this date, clear the time and return it
718 @return {Date} this or the clone
720 clearTime : function(clone){
722 return this.clone().clearTime();
727 this.setMilliseconds(0);
732 * Provides a convenient method of performing basic date arithmetic. This method
733 * does not modify the Date instance being called - it creates and returns
734 * a new Date instance containing the resulting date value.
739 var dt = new Date('10/29/2006').add(Date.DAY, 5);
740 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
742 //Negative values will subtract correctly:
743 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
744 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
746 //You can even chain several calls together in one line!
747 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
748 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
751 * @param {String} interval A valid date interval enum value
752 * @param {Number} value The amount to add to the current date
753 * @return {Date} The new Date instance
755 add : function(interval, value){
756 var d = this.clone();
757 if (!interval || value === 0) return d;
758 switch(interval.toLowerCase()){
760 d.setMilliseconds(this.getMilliseconds() + value);
763 d.setSeconds(this.getSeconds() + value);
766 d.setMinutes(this.getMinutes() + value);
769 d.setHours(this.getHours() + value);
772 d.setDate(this.getDate() + value);
775 var day = this.getDate();
777 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
780 d.setMonth(this.getMonth() + value);
783 d.setFullYear(this.getFullYear() + value);
790 load = function(ar) {
792 imports.lang.copyPropertiesNoOverwrite( date,ar);
793 imports.lang.copyPropertiesNoOverwrite(datePrototype, ar.prototype);
797 // non imports version.
798 for(i in datePrototype) {
799 if (!Date.prototype[i]) {
800 Date.prototype[i] = datePrototype[i];