JavaScript Date Instance Methods (v3.3 December 2011)

Looking for version 2?

Contents

  1. Introduction
  2. Demo
  3. Github Repository
  4. Download
  5. Examples
  6. Method Reference
  7. Parsable Formats
  8. Format Codes
  9. Customization and I18n
  10. Unit Tests

contents ^

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 are welcome through my Github Repository

Features include:

  1. Parse various formats with ability to register custom format parsing.
  2. Format dates using the well-known percent-letter formatting options with the ability to register custom formating.
  3. Add and subtract years, months, days, hours, minutes or seconds.
  4. Calculate differences between dates in the given unit.
  5. Methods are available on all Date Objects.

contents ^

Demo

$D("").strftime("") =

$D("").add(, "").strftime("%Y-%m-%d %H:%M:%S") =

$D("").diff("", "", ) =

contents ^

Download

contents ^

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

contents ^

Full Reference

New Date Instance Methods
MethodDescription
Date#add(iAmount[, sUnit='day']) -> DateAlters the date by adding an amount expressed in the given unit.
Date#strftime(sFormat) -> StringReturns the date expressed in a string according to the given format.
Date#diff(date[, sUnit='day'][, bAllowDecimal=false]) -> NumberReturns the amount difference between the given date in the given format. Round toward zero unless bAllowDecimal is true.
Date#diffText() -> StringReturns a string with a conversational date string such as "5 days ago".
Date#clone() -> DateReturns a date object with the same value.
Date#succ([sUnit='day']) -> DateReturns a copy of the date incremented by one day (or any other unit).
Date#getShortYear() -> NumberReturns number of years past the century (one or two digit year).
Date#getMonthNumber() -> NumberReturns the number of the month 1-12.
Date#getMonthName() -> StringReturns the name of the month as defined in Date.MONTHNAMES.
Date#getAbbrMonthName() -> StringReturns the abreviated name of the month as defined in Date.ABBR_MONTHNAMES.
Date#getDayName() -> StringReturns the name of the day of the week as defined in Date.DAYNAMES.
Date#getAbbrDayName() -> StringReturns the abbreviated name of the day of the week as defined in Date.ABBR_DAYNAMES.
Date#getDayOrdinal() -> StringReturns the ordinal suffix for the day of the month as defined in Date.ORDINALNAMES.
Date#getHours12() -> StringReturns hours in 12-hour format.
Date#getAmPm() -> StringReturns AM or PM for the date.
Date#getUnix() -> NumberReturns the number of seconds past 1970-01-01-00:00:00.
Date#getGmtOffset() -> StringReturns the minutes and seconds offset from GMT.
Date#getTimezoneName() -> StringReturns the browser-reported name of the timezone.
Date#toYmdInt() -> NumberReturns an integer in the format YYYYMMDD (useful for quickly sorting by date)
New Date Static Properties
PropertyDescription
Date.create(date) -> Datedate can be a parsable string, a unix timestamp or a Date object.
Date.MONTHNAMESAn array of the month names
Date.ABBR_MONTHNAMESAn array of the abbreviated month names
Date.DAYNAMESAn array of the names of the days of the week
Date.ABBR_DAYNAMESAn array of the abbreviated names of the days of the week
Date.ORDINALNAMESAn array of the ordinal suffixes for digits 0-9
Date.ISOA shortcut for ISO-8601 date format (%Y-%m-%dT%H:%M:%S.%s%G)
Date.SQLA shortcut for SQL date format (%Y-%m-%d %H:%M:%S)
Date.SCRIPT_LOADA date object representing when the script was loaded
Date.daysInMonth(iYear, iMonth) -> NumberGiven a four digit year and a month 1-12, how many days are in that month
Date.autoFormat(sInput, sFormatStr) -> HTMLElementGiven an element id or object, make an input auto-format input into a date on blur
Date.addFormat(sName, oRules) -> ObjectAdd a set of format codes and a method called sName to accept the rules (see customization)
Date.current() -> DateReturn a Date object representing the date at that moment
Date.create.patternsAn object with pairs defining parsers for custom formats (see customization)
Native Date Instance Methods (from w3schools.com)
MethodDescription
Date#getDate() -> NumberReturns the day of the month from a Date object (from 1-31)
Date#getDay() -> NumberReturns the day of the week from a Date object (from 0-6)
Date#getMonth() -> NumberReturns the month from a Date object (from 0-11)
Date#getFullYear() -> NumberReturns the year, as a four-digit number, from a Date object
Date#getYear() -> NumberReturns the year, as a two-digit or a four-digit number, from a Date object. Use Date#getFullYear instead !!
Date#getHours() -> NumberReturns the hour of a Date object (from 0-23)
Date#getMinutes() -> NumberReturns the minutes of a Date object (from 0-59)
Date#getSeconds() -> NumberReturns the seconds of a Date object (from 0-59)
Date#getMilliseconds() -> NumberReturns the milliseconds of a Date object (from 0-999)
Date#getTime() -> NumberReturns the number of milliseconds since midnight Jan 1, 1970
Date#getTimezoneOffset() -> NumberReturns the difference in minutes between local time and Greenwich Mean Time (GMT)
Date#getUTCDate() -> NumberReturns the day of the month from a Date object according to universal time (from 1-31)
Date#getUTCDay() -> NumberReturns the day of the week from a Date object according to universal time (from 0-6)
Date#getUTCMonth() -> NumberReturns the month from a Date object according to universal time (from 0-11)
Date#getUTCFullYear() -> NumberReturns the four-digit year from a Date object according to universal time
Date#getUTCHours() -> NumberReturns the hour of a Date object according to universal time (from 0-23)
Date#getUTCMinutes() -> NumberReturns the minutes of a Date object according to universal time (from 0-59)
Date#getUTCSeconds() -> NumberReturns the seconds of a Date object according to universal time (from 0-59)
Date#getUTCMilliseconds() -> NumberReturns the milliseconds of a Date object according to universal time (from 0-999)
Date#setDate(iDayOfMonth) -> NumberSets the day of the month in a Date object (from 1-31)
Date#setMonth(iMonth) -> NumberSets the month in a Date object (from 0-11)
Date#setFullYear(iYear) -> NumberSets the year in a Date object (four digits)
Date#setYear(sYear) -> NumberSets the year in the Date object (two or four digits). Use Date#setFullYear instead !!
Date#setHours(iHour[, iMinute][, iSecond][, iMillisecond]) -> NumberSets the hour in a Date object (from 0-23)
Date#setMinutes(iMinute[, iSecond][, iMillisecond]) -> NumberSet the minutes in a Date object (from 0-59)
Date#setSeconds(iSecond[, iMillisecond]) -> NumberSets the seconds in a Date object (from 0-59)
Date#setMilliseconds(iMillisecond) -> NumberSets the milliseconds in a Date object (from 0-999)
Date#setTime(iMillisecond) -> NumberCalculates a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970
Date#toISOString() -> StringES5. Date converted to UTC time and formatted as ISO-8601 string (%Y-%m-%dT%H:%M:%S.%N%G)
Date#setUTCDate(iDay) -> NumberSets the day of the month in a Date object according to universal time (from 1-31)
Date#setUTCMonth(iMonth) -> NumberSets the month in a Date object according to universal time (from 0-11)
Date#setUTCFullYear(iYear) -> NumberSets the year in a Date object according to universal time (four digits)
Date#setUTCHours(iHour[, iMinute][, iSecond][, iMillisecond]) -> NumberSets the hour in a Date object according to universal time (from 0-23)
Date#setUTCMinutes(iMinute[, iSecond][, iMillisecond]) -> NumberSet the minutes in a Date object according to universal time (from 0-59)
Date#setUTCSeconds(iSecond[, iMillisecond]) -> NumberSet the seconds in a Date object according to universal time (from 0-59)
Date#setUTCMilliseconds(iMillisecond) -> NumberSets the milliseconds in a Date object according to universal time (from 0-999)
Date#toString() -> StringConverts a Date object to a string
Date#toGMTString() -> StringConverts a Date object, according to Greenwich time, to a string. Use Date#toUTCString instead !!
Date#toUTCString() -> StringConverts a Date object, according to universal time, to a string
Date#toLocaleString() -> StringConverts a Date object, according to local time, to a string
Date#valueOf() -> NumberReturns 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) -> NumberTakes a date string and returns the number of milliseconds since midnight of January 1, 1970
Date.UTC(year,month,day,hours,minutes,seconds,ms) -> NumberTakes a date and returns the number of milliseconds since midnight of January 1, 1970 according to universal time

contents ^

Parsable Formats

Note: all formats are case insensitive.

contents ^

Format Codes

#strftime()#formatPhp()#formatSql()*ExampleMeaning
Year
%YYyyyy2008Four-digit year
%yyyy08Two-digit year
Month
%mmmm09Two-digit month
%#mnm9One or two-digit month
%BFmmmmSeptemberFull month name
%bMmmmSepAbbreviated month name
Day
%dddd05Two-digit day of month
%#djd5One or two-digit day of month
%e 5One or two-digit day of month
%AlddddSundayFull name of the day of the week
%aDdddSunAbbreviated name of the day of the week
%www0Number of the day of the week (0 = Sunday, 6 = Saturday)
%oD thThe ordinal suffix string following the day of the month
Hour
%HHhh2423Hours in 24-hour format (two digits)
%#HGh243Hours in 24-hour integer format (one or two digits)
%Ihhh or hh1211Hours in 12-hour format (two digits)
%#Igh123Hours in 12-hour integer format (one or two digits)
%pAam or pmPMAM or PM
apmam or pm
Minute
%Mimi09Minutes (two digits)
%#M 9Minutes (one or two digits)
Second
%Ssss02Seconds (two digits)
%#S 2Seconds (one or two digits)
%sU 1206567625723Unix timestamp (Seconds past 1970-01-01 00:00:00)
Millisecond
%N 008Milliseconds (three digits)
%#N 8Milliseconds (one to three digits)
Timezone
%OZ 360difference in minutes between local time and GMT
%ZE Mountain Standard TimeName of timezone as reported by browser
%GP -06:00Hours 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:00Y-m-d\TH:i:sP (iso 8601)
r Sat, 23 Oct 2010 14:46:03 -0600D, j M Y H:i:s O (rfc 2822 - Internet Message Format)
Characters
%n \nNewline
%t \tTab
%% %Percent Symbol

*Note: formatSql() codes may be uppercase or lowercase.

contents ^

Customization

This 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 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'
}
});