JavaScript Date Instance Methods (v2.0.2 2008-09-10)

Contents

  1. Introduction
  2. Demo
  3. Download Source
  4. More Examples
  5. Method Reference
  6. Parsable Formats
  7. Format Codes
  8. Customization
  9. Unit Test

contents ^

Introduction

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:

  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 Source

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

contents ^

More 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').strftime('%Y-%m-%d %H:%M:%S'); // "2006-09-21 00:15:00"
$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#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.daysInMonth(iYear, iMonth) -> NumberGiven a four digit year and a month 1-12, how many days are in that month
Date.prototype.strftime.formatCodesAn object with pairs defining format codes (see customization)
Date.prototype.strftime.formatShortcutsAn object with pairs defining format shortcuts (see customization)
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#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(iDate) -> 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

CodeExampleMeaning
Year
%Y2008Four-digit year
%y08Two-digit year
Month
%m09Two-digit month
%#m9One or two-digit month
%BSeptemberFull month name
%bSepAbbreviated month name
Day
%d05Two-digit day of month
%#d5One or two-digit day of month
%e5One or two-digit day of month
%ASundayFull name of the day of the week
%aSunAbbreviated name of the day of the week
%w0Number of the day of the week (0 = Sunday, 6 = Saturday)
%othThe ordinal suffix string following the day of the month
Hour
%H23Hours in 24-hour format (two digits)
%#H3Hours in 24-hour integer format (one or two digits)
%I11Hours in 12-hour format (two digits)
%#I3Hours in 12-hour integer format (one or two digits)
%pPMAM or PM
Minute
%M09Minutes (two digits)
%#M9Minutes (one or two digits)
Second
%S02Seconds (two digits)
%#S2Seconds (one or two digits)
%s1206567625723Unix timestamp (Seconds past 1970-01-01 00:00:00)
Millisecond
%N008Milliseconds (three digits)
%#N8Milliseconds (one to three digits)
Timezone
%O360difference in minutes between local time and GMT
%ZMountain Standard TimeName of timezone as reported by browser
%G-06:00Hours and minutes between GMT
Shortcuts
%F2008-03-26%Y-%m-%d
%T05:06:30%H:%M:%S
%X05:06:30%H:%M:%S
%x03/26/08%m/%d/%y
%D03/26/08%m/%d/%y
%#cWed Mar 26 15:31:00 2008%a %b %e %H:%M:%S %Y
%v3-Sep-2008%e-%b-%Y
%R15:31%H:%M
%r3:31:00 PM%I:%M:%S %p
Characters
%n\nNewline
%t\tTab
%%%Percent Symbol

contents ^

Customization

This library allows you to customize month/day names, parsing patterns and format characters.

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(' '),

Parsing patterns

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]);
});

Format characters

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