转载自http://sandbox.kendsnyder.com/date/?q=sandbox/date/
JavaScript Date Instance Methods (v3.4.1 June 2012)
Looking for version 2?
Contents
- Introduction
- Demo
- Github Repository
- Download
- Examples
- Method Reference
- Parsable Formats
- Format Codes
- Customization and I18n
- Unit Tests
- MIT License
Introduction
This script provides JavaScript Date instance methods for parsing, formatting, and calculating dates. It leverages the existing functionality of the native Date.parse method and uses a concise and configurable algorithm for interpreting format codes.
Contributions and bug reports are welcome on the Github Repository
Features include:
- Parse various formats with ability to register custom format parsing.
- Format dates using the well-known percent-letter formatting options with the ability to register custom formating.
- Add and subtract years, months, days, hours, minutes, seconds, or milliseconds.
- Calculate differences between dates in the given unit.
- Methods are available on all Date Objects.
Demo
Download
Examples
$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').format('%Y-%m-%d %H:%M:%S'); // "2006-09-21 00:15:00" $D('2006-09-20').format('m/d/Y'); // "09/20/2006" $D('2006.09.28').diff('20 Sep, 2006', 'days'); // 8
Full Reference
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#diffText() -> String | Returns a string with a conversational date string such as "5 days ago". |
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) |
Date#setUTCOffsetString(sOffset) -> Date | Set the UTC offset with a four-digit string such as `+04:00` or `-0700` |
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.SCRIPT_LOAD | A date object representing when the script was loaded |
Date.daysInMonth(iYear, iMonth) -> Number | Given a four digit year and a month 1-12, how many days are in that month |
Date.autoFormat(sInput, sFormatStr) -> HTMLElement | Given an element id or object, make an input auto-format input into a date on blur |
Date.addFormat(sName, oRules) -> Object | Add a set of format codes and a method called sName to accept the rules (see customization) |
Date.current() -> Date | Return a Date object representing the date at that moment |
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#toISOString() -> String | ES5. Date converted to UTC time and formatted as ISO-8601 string (%Y-%m-%dT%H:%M:%S.%N%G) |
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) | |
Method | Description |
Date.parse(sDate) -> Number | Takes a date string and returns the number of milliseconds since midnight of January 1, 1970 |
Date.UTC(year,month,day,hours,minutes,seconds,ms) -> Number | Takes a date and returns the number of milliseconds since midnight of January 1, 1970 according to universal time |
Parsable Formats
- 5/29/2007
- 05/29/2007
- 5-29-2007
- 05-29-2007
- Oct 29, 2007
- October 29, 2007
- October the 29th
- October 29th
- 29 Oct 2007
- 29-Oct-2007
- 29 October 2007
- 29-October-2007
- 2007-10-29
- 29.10.2007
- 29/10/2007
date
02:30:59.005date
02:30:59date
02:30date
2:30:59amdate
2:30amdate
2am- 2:30:59am
- 2:30am
- 2am
- 2010-03-15T12:34:56.005
- Thu, 21 Dec 2000 16:01:07 +0200 (RFC 2822 format)
- 2010-03-15T12:34:56+01:00 (full ISO 8601)
- Sat Apr 14 2012 09:45:25 GMT-0600 (MDT)
- @1312132465 (Unix Timestamp)
- /Date(1296824894000)/ (ASP JSON)
- /Date(1296824894000-0700)/ (ASP JSON)
- 2 weeks before
date
- 2 years after
date
- 2 days ago
- in 2 months
- +2 months
- -2 days
- now
- yesterday
- today
- tomorrow
- last Thursday
- this Thursday
- last month
Note: all formats are case insensitive.
Format Codes
#strftime() | #formatPhp() | #formatSql()† | Example | Meaning |
---|---|---|---|---|
Year | ||||
%Y | Y | yyyy | 2008 | Four-digit year |
%y | y | yy | 08 | Two-digit year |
Month | ||||
%m | m | mm | 09 | Two-digit month |
%#m | n | m | 9 | One or two-digit month |
%B | F | mmmm | September | Full month name |
%b | M | mmm | Sep | Abbreviated month name |
Day | ||||
%d | d | dd | 05 | Two-digit day of month |
%#d | j | d | 5 | One or two-digit day of month |
%e | 5 | One or two-digit day of month | ||
%A | l | dddd | Sunday | Full name of the day of the week |
%a | D | ddd | Sun | Abbreviated name of the day of the week |
%w | w | w | 0 | Number of the day of the week (0 = Sunday, 6 = Saturday) |
%o | D | th | The ordinal suffix string following the day of the month | |
Hour | ||||
%H | H | hh24 | 23 | Hours in 24-hour format (two digits) |
%#H | G | h24 | 3 | Hours in 24-hour integer format (one or two digits) |
%I | h | hh or hh12 | 11 | Hours in 12-hour format (two digits) |
%#I | g | h12 | 3 | Hours in 12-hour integer format (one or two digits) |
%p | A | am or pm | PM | AM or PM |
a | pm | am or pm | ||
Minute | ||||
%M | i | mi | 09 | Minutes (two digits) |
%#M | 9 | Minutes (one or two digits) | ||
Second | ||||
%S | s | ss | 02 | Seconds (two digits) |
%#S | 2 | Seconds (one or two digits) | ||
%s | U | 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 | Z | 360 | difference in minutes between local time and GMT | |
%Z | E | EST | Name of timezone as reported by browser | |
%G | P | -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 | ||
c | 2008-03-26T15:31:00-07:00 | Y-m-d\TH:i:sP (iso 8601) | ||
r | Sat, 23 Oct 2010 14:46:03 -0600 | D, j M Y H:i:s O (rfc 2822 - Internet Message Format) | ||
Literals | ||||
%n | \n | Newline | ||
%t | \t | Tab | ||
%% | % | Percent Symbol |
†formatSql()
codes may be uppercase or lowercase.
Customization
The Date Prototype library allows you to customize month/day names, parsing patterns and format characters.
Parsing patterns
Add new pattern strings or functions to the array defined in Data.create.patterns. See source for more examples.
Date.addPattern(['month-year', /^(\d{1,2})-(\d{4})$/, '$1/01/$2']); // match month-year Date.addPattern(['hoy', /^hoy$/i, function(match) { return new Date(); }], 'iso_8601'); // match Spanish word for `today`
Remove a pattern
Date.removePattern('us'); // us-style m/d/Y dates no longer recognized var us = Date.removePattern('us'); Date.addPattern(us, 'world'); // prefer world-style d/m/Y dates over us-style m/d/Y dates
Internationalize Month/day names
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(' ');
Format characters
Add new characters and character patterns and a method to call them. Here is a snippet from the source.
Date.addFormat('formatPhp', { // // 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) // matcher: /(\\)?([a-z])/i, defaultFormat: 'Y-m-d H:i:s', codes: { // year Y: 'FullYear', // ... O: 'UTCOffsetNumber' }, // // 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 // shortcuts: { // iso c: 'Y-m-d\\TH:i:sP', // rfc 2822 r: 'D, j M Y H:i:s O' } });
© 2012 Ken Snyder, kendsnyder.com