This script provides JavaScript Date instance methods for parsing, formatting, and calculating dates. The script is compact (6.1kb) because it levarages the existing functionality of the native Date.parse method and uses a concise and configurable algorithm for interpolating format codes.
Features include:
| File | Commented Source | Compressed Source |
|---|---|---|
| Date and Date.prototype methods (v2.0.2) | date.commented.js | date.js 6.1kb |
| Date.create.patterns plugin (additional string date recognition) | date.patterns.commented.js | date.patterns.js 1.8kb |
$D('2006-09-20').strftime('%m/%d/%Y'); // "09/20/2006"
$D('Sep 20 2006').add(3).strftime('%Y-%m-%d'); // "2006-09-23"
$D('09/20/2006').add(4, 'years').strftime('%Y-%m-%d'); // "2010-09-20"
$D('09/20/2006 20:15:00').add(4, 'hours').strftime('%Y-%m-%d %H:%M:%S'); // "2006-09-21 00:15:00"
$D('2006.09.28').diff('20 Sep, 2006', 'days'); // 8
| New Date Instance Methods | |
|---|---|
| Method | Description |
| Date#add(iAmount[, sUnit='day']) -> Date | Alters the date by adding an amount expressed in the given unit. |
| Date#strftime(sFormat) -> String | Returns the date expressed in a string according to the given format. |
| Date#diff(date[, sUnit='day'][, bAllowDecimal=false]) -> Number | Returns the amount difference between the given date in the given format. Round toward zero unless bAllowDecimal is true. |
| Date#clone() -> Date | Returns a date object with the same value. |
| Date#succ([sUnit='day']) -> Date | Returns a copy of the date incremented by one day (or any other unit). |
| Date#getShortYear() -> Number | Returns number of years past the century (one or two digit year). |
| Date#getMonthNumber() -> Number | Returns the number of the month 1-12. |
| Date#getMonthName() -> String | Returns the name of the month as defined in Date.MONTHNAMES. |
| Date#getAbbrMonthName() -> String | Returns the abreviated name of the month as defined in Date.ABBR_MONTHNAMES. |
| Date#getDayName() -> String | Returns the name of the day of the week as defined in Date.DAYNAMES. |
| Date#getAbbrDayName() -> String | Returns the abbreviated name of the day of the week as defined in Date.ABBR_DAYNAMES. |
| Date#getDayOrdinal() -> String | Returns the ordinal suffix for the day of the month as defined in Date.ORDINALNAMES. |
| Date#getHours12() -> String | Returns hours in 12-hour format. |
| Date#getAmPm() -> String | Returns AM or PM for the date. |
| Date#getUnix() -> Number | Returns the number of seconds past 1970-01-01-00:00:00. |
| Date#getGmtOffset() -> String | Returns the minutes and seconds offset from GMT. |
| Date#getTimezoneName() -> String | Returns the browser-reported name of the timezone. |
| Date#toYmdInt() -> Number | Returns an integer in the format YYYYMMDD (useful for quickly sorting by date) |
| New Date Static Properties | |
| Property | Description |
| Date.create(date) -> Date | date can be a parsable string, a unix timestamp or a Date object. |
| Date.MONTHNAMES | An array of the month names |
| Date.ABBR_MONTHNAMES | An array of the abbreviated month names |
| Date.DAYNAMES | An array of the names of the days of the week |
| Date.ABBR_DAYNAMES | An array of the abbreviated names of the days of the week |
| Date.ORDINALNAMES | An array of the ordinal suffixes for digits 0-9 |
| Date.ISO | A shortcut for ISO-8601 date format (%Y-%m-%dT%H:%M:%S.%s%G) |
| Date.SQL | A shortcut for SQL date format (%Y-%m-%d %H:%M:%S) |
| Date.daysInMonth(iYear, iMonth) -> Number | Given a four digit year and a month 1-12, how many days are in that month |
| Date.prototype.strftime.formatCodes | An object with pairs defining format codes (see customization) |
| Date.prototype.strftime.formatShortcuts | An object with pairs defining format shortcuts (see customization) |
| Date.create.patterns | An object with pairs defining parsers for custom formats (see customization) |
| Native Date Instance Methods (from w3schools.com) | |
| Method | Description |
| Date#getDate() -> Number | Returns the day of the month from a Date object (from 1-31) |
| Date#getDay() -> Number | Returns the day of the week from a Date object (from 0-6) |
| Date#getMonth() -> Number | Returns the month from a Date object (from 0-11) |
| Date#getFullYear() -> Number | Returns the year, as a four-digit number, from a Date object |
| Date#getYear() -> Number | Returns the year, as a two-digit or a four-digit number, from a Date object. Use Date#getFullYear instead !! |
| Date#getHours() -> Number | Returns the hour of a Date object (from 0-23) |
| Date#getMinutes() -> Number | Returns the minutes of a Date object (from 0-59) |
| Date#getSeconds() -> Number | Returns the seconds of a Date object (from 0-59) |
| Date#getMilliseconds() -> Number | Returns the milliseconds of a Date object (from 0-999) |
| Date#getTime() -> Number | Returns the number of milliseconds since midnight Jan 1, 1970 |
| Date#getTimezoneOffset() -> Number | Returns the difference in minutes between local time and Greenwich Mean Time (GMT) |
| Date#getUTCDate() -> Number | Returns the day of the month from a Date object according to universal time (from 1-31) |
| Date#getUTCDay() -> Number | Returns the day of the week from a Date object according to universal time (from 0-6) |
| Date#getUTCMonth() -> Number | Returns the month from a Date object according to universal time (from 0-11) |
| Date#getUTCFullYear() -> Number | Returns the four-digit year from a Date object according to universal time |
| Date#getUTCHours() -> Number | Returns the hour of a Date object according to universal time (from 0-23) |
| Date#getUTCMinutes() -> Number | Returns the minutes of a Date object according to universal time (from 0-59) |
| Date#getUTCSeconds() -> Number | Returns the seconds of a Date object according to universal time (from 0-59) |
| Date#getUTCMilliseconds() -> Number | Returns the milliseconds of a Date object according to universal time (from 0-999) |
| Date#setDate(iDayOfMonth) -> Number | Sets the day of the month in a Date object (from 1-31) |
| Date#setMonth(iMonth) -> Number | Sets the month in a Date object (from 0-11) |
| Date#setFullYear(iYear) -> Number | Sets the year in a Date object (four digits) |
| Date#setYear(sYear) -> Number | Sets the year in the Date object (two or four digits). Use Date#setFullYear instead !! |
| Date#setHours(iHour[, iMinute][, iSecond][, iMillisecond]) -> Number | Sets the hour in a Date object (from 0-23) |
| Date#setMinutes(iMinute[, iSecond][, iMillisecond]) -> Number | Set the minutes in a Date object (from 0-59) |
| Date#setSeconds(iSecond[, iMillisecond]) -> Number | Sets the seconds in a Date object (from 0-59) |
| Date#setMilliseconds(iMillisecond) -> Number | Sets the milliseconds in a Date object (from 0-999) |
| Date#setTime(iMillisecond) -> Number | Calculates a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970 |
| Date#setUTCDate(iDay) -> Number | Sets the day of the month in a Date object according to universal time (from 1-31) |
| Date#setUTCMonth(iMonth) -> Number | Sets the month in a Date object according to universal time (from 0-11) |
| Date#setUTCFullYear(iYear) -> Number | Sets the year in a Date object according to universal time (four digits) |
| Date#setUTCHours(iHour[, iMinute][, iSecond][, iMillisecond]) -> Number | Sets the hour in a Date object according to universal time (from 0-23) |
| Date#setUTCMinutes(iMinute[, iSecond][, iMillisecond]) -> Number | Set the minutes in a Date object according to universal time (from 0-59) |
| Date#setUTCSeconds(iSecond[, iMillisecond]) -> Number | Set the seconds in a Date object according to universal time (from 0-59) |
| Date#setUTCMilliseconds(iMillisecond) -> Number | Sets the milliseconds in a Date object according to universal time (from 0-999) |
| Date#toString() -> String | Converts a Date object to a string |
| Date#toGMTString() -> String | Converts a Date object, according to Greenwich time, to a string. Use Date#toUTCString instead !! |
| Date#toUTCString() -> String | Converts a Date object, according to universal time, to a string |
| Date#toLocaleString() -> String | Converts a Date object, according to local time, to a string |
| Date#valueOf() -> Number | Returns the number of milliseconds since midnight Jan 1, 1970 (same as Date#getTime) |
| Note: the Number returned by native Date setters is the number of milliseconds since midnight Jan 1, 1970. | |
| Native Date Static Methods (from w3schools.com) | |
| Date.parse(sDate) -> Number | Takes a date string and returns the number of milliseconds since midnight of January 1, 1970 |
| Date.UTC(iDate) -> Number | Takes a date and returns the number of milliseconds since midnight of January 1, 1970 according to universal time |
Note: all formats are case insensitive.
| Code | Example | Meaning |
|---|---|---|
| Year | ||
| %Y | 2008 | Four-digit year |
| %y | 08 | Two-digit year |
| Month | ||
| %m | 09 | Two-digit month |
| %#m | 9 | One or two-digit month |
| %B | September | Full month name |
| %b | Sep | Abbreviated month name |
| Day | ||
| %d | 05 | Two-digit day of month |
| %#d | 5 | One or two-digit day of month |
| %e | 5 | One or two-digit day of month |
| %A | Sunday | Full name of the day of the week |
| %a | Sun | Abbreviated name of the day of the week |
| %w | 0 | Number of the day of the week (0 = Sunday, 6 = Saturday) |
| %o | th | The ordinal suffix string following the day of the month |
| Hour | ||
| %H | 23 | Hours in 24-hour format (two digits) |
| %#H | 3 | Hours in 24-hour integer format (one or two digits) |
| %I | 11 | Hours in 12-hour format (two digits) |
| %#I | 3 | Hours in 12-hour integer format (one or two digits) |
| %p | PM | AM or PM |
| Minute | ||
| %M | 09 | Minutes (two digits) |
| %#M | 9 | Minutes (one or two digits) |
| Second | ||
| %S | 02 | Seconds (two digits) |
| %#S | 2 | Seconds (one or two digits) |
| %s | 1206567625723 | Unix timestamp (Seconds past 1970-01-01 00:00:00) |
| Millisecond | ||
| %N | 008 | Milliseconds (three digits) |
| %#N | 8 | Milliseconds (one to three digits) |
| Timezone | ||
| %O | 360 | difference in minutes between local time and GMT |
| %Z | Mountain Standard Time | Name of timezone as reported by browser |
| %G | -06:00 | Hours and minutes between GMT |
| Shortcuts | ||
| %F | 2008-03-26 | %Y-%m-%d |
| %T | 05:06:30 | %H:%M:%S |
| %X | 05:06:30 | %H:%M:%S |
| %x | 03/26/08 | %m/%d/%y |
| %D | 03/26/08 | %m/%d/%y |
| %#c | Wed Mar 26 15:31:00 2008 | %a %b %e %H:%M:%S %Y |
| %v | 3-Sep-2008 | %e-%b-%Y |
| %R | 15:31 | %H:%M |
| %r | 3:31:00 PM | %I:%M:%S %p |
| Characters | ||
| %n | \n | Newline |
| %t | \t | Tab |
| %% | % | Percent Symbol |
This library allows you to customize month/day names, parsing patterns and format characters.
Simply set the static members of the Date object.
Date.MONTHNAMES = 'Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre'.split(' '),
Date.DAYNAMES = 'Domingo Lunes Martes Mi�rcoles Jueves Viernes S�bado'.split(' '),
Add new pattern strings or functions to the array defined in Data.create.patterns. See source for more examples.
// World time => Parsable US-style time
Date.create.patterns.unshift([/(3[01]|[0-2]\d)\s*\.\s*(1[0-2]|0\d)\s*\.\s*([1-9]\d{3})/, '$2/$1/$3']);
// 5 months ago
Date.create.patterns.push(function (str) {
var match = str.match(/(\d+)\s+(year|month|week|day|hour|minute|second)s?\s+ago/i);
if (match) return new Date().add(-1 * match[1], match[2]);
});
Add new characters and character patterns for use with strftime. See source for more examples.
//
// 2-part regex matcher for format codes
//
// first match must be the character before the code (to account for escaping)
// second match must be the format code character(s)
//
Date.prototype.strftime.formatCodes = {
matcher: /()([a-z]{2,4})/,
// year
yyyy: 'FullYear',
yy: 'ShortYear.2',
// month
mm: 'MonthNumber.2',
// day
dd: 'Date.2'
};
//
// shortcuts that will be translated into their longer version
//
// be sure that format shortcuts do not refer to themselves: this will cause an infinite loop
//
Date.prototype.strftime.formatShortcuts = {
us: 'mm/dd/yyyy',
de: 'mm.dd.yyyy',
iso: 'yyyy-mm-dd'
};