DP_DateExtensions Library

Download | Revision History | Usage | Methods | Examples

The DP_DateExtensions library extends the JavaScript Date object with new features and functionality.

  • The addition of feature-rich timeFormat() and dateFormat() methods allowing you detailed control over the display of your date and time values.
  • Easy manipulation of dates via the add() and diff() methods including full understanding of business days.
  • Simplified comparision of dates using the new compare() method.
  • The ability to parse several ISO 8601 standard format dates as described in the Date and Time Formats W3C note.

Download back to top

This component requires a JavaScript (ECMAScript) 1.3 (or better) development environment. All downloads and code are covered by our Source Code Policy.

DP_DateExtensions.zip, 12.00kb Zip-Format Archive

Revision History back to top

April 15, 2008

  • Fixed several regular expression bugs in the new parseFormat() function.
  • The new parseHttpTimeFormat() function was mistakenly made an instance function. It's now a static function as intended.

April 15, 2008

  • Fixed several bugs related to the new Mask characters.
  • Fixed several regular expression bugs in the new parseFormat() function.
  • Added a parameter to the parseFormat() function allowing the developer to choose from several default values for missing date parts.
  • Added the parseHttpTimeFormat() function.

April 13, 2008

There are some major changes in this version which may invalidate existing code. Please read the change log carefully.

  • Added a new parseFormat() function which accepts a data/time mask and a string value. If the mask matches the input will be converted to a date and returned.
  • Changed the mask characters used in the dateFormat() function to make the characters used unique across the date and time functions (allowing them to be used in the new parseFormat() function). All of the dateFormat() characters are uppercase and MOST of the timeFormat() characters are lowercase. See the documentation for specifics.
  • The lowercase "t" and the space have been added as seperator characters to the parseIso8601() function. This does represent a break from the standard (the ISO 8601 standard only allows for a captital "T") but has been requested by several users and does not affect processing of standard values.

June 25, 2007

  • iso8601Format() nows accepts, as alternative input, the numbers 1-6 which correspond to the (sometimes cumbersome) letter codes.
  • The iso8601Format() "Style" parameter is now optional and will default to "YMDHMSM" if not present.

May 13, 2007

  • Added the httpTimeFormat() method.
  • Added the isLeapYear() method.
  • Added the isWeekday() method.
  • Added the weekOfYear() method.

February 19, 2007

  • Fixed a bug in the dateFormat() and timeFormat() methods concerning masks with concatinated date parts.

October 19, 2006

  • Added the Date.is() method.

September 28, 2006

  • Fixed a bug in the "add()" method concerning businessdays... it didn't work. It does now. Thanks to Jonathan Hicks for pointing out my stupidity.

September 20, 2006

  • Added the ability to recogonize a space or a lowercase "t" as a date/time separator in the parseIso8601() method. In other words in addition to "2006-06-21T14:46:34-05:00" the method will now also recognize "2006-06-21 14:46:34-05:00" and "2006-06-21t14:46:34-05:00".

July 12, 2006

  • Added the "quarterhours" (or, if you'd like to be cute, the "warhols") and "halfhours" timespans to the add() and diff() methods.

July 10, 2006

  • Added the add(), diff(), compare() and dayOfYear() methods.
  • Fixed several small bugs.

June 21, 2006

  • Initial Release.

Usage back to top

The library consists of a single JavaScript file with a .JS extension.

Importing the Library

The library must be imported before it is used. To import the library use the <script> tag. For example:
<script type="text/javascript" src="DP_DateExtensions.js"></script>.

Your path may vary depending on the location of the script on your server.

Using the Library

Once the library has been imported you may access any of the functions within it. Some of the functions are extensions of the Date Object while others are extensions of the Date Object prototype. Extensions to the Date Object are accessible via the Date object like so:

var MyFormattedDate = Date.parseIso8601(new Date());

Extensions to the Date Object prototype are accessible directly as methods of any instantiated date object:

var MyDate = new Date();
var MyFormattedDate = MyDate.dateFormat("mmm d, yyyy");

Methods back to top

There are several methods currently available in the library. Static methods of Date:

Instance methods of Date objects:

Note that in method signatures a pipe ("|") indicates "OR" while arguments in square brackets are optional.

Date.is()

This static method returns "true" if the passed value is a JavaScript Date object.

Method Signature

Date.is(Input)

Arguments

  • Input: Any, Required. A JavaScript value.

Return

Boolean. Returns true of the passed value is a JacaScript Date object, false if not.

Date.parseFormat()

This static method accepts a date/time mask and a string value. The passed value is first checked against the mask; if it matches then the value is converted to a native JavaScript date object.

When creating the date any ambigious or unsupplied values will use default values (as defined by the Default parameter). Some mask parts (such as "DDD", "DDDD", "TT", etc) are ambigious by nature and will not inform the date creation. They are useful for recognizing the date format however (allowing this function to parse any output of the dateFormat() and timeFormat() functions with no manipulation). Also note that the mask must match the input exactly, including any spaces, for the conversion step to be attempted.

Method Signature

Date.parseFormat(Input, Mask, Default)

Arguments

  • Input: String, Required. A string representing the date you wish to parse.
  • Mask: String, Required. A mask representing the date format to convert. All mask characters used by the dateFormat() and timeFormat() functions are accepted:
    • D: The day of the month as a number.
    • DD: The day of the month as a number with, if applicable, a leading zero.
    • DDD: The day of the week as a three-character abbreviation (for example "Tue").
    • DDDD: The full name of the day of the week (for example "Tuesday").
    • M: The month as a number.
    • MM: The month as a number with, if applicable, a leading zero.
    • MMM: The month as a three-character abbreviation (for example "Jan").
    • MMMM: The full name of the month (for example "January").
    • YY: The last two digits of the year.
    • YYYY: The four-digit year.
    • h: Hours. 12-hour clock.
    • hh: Hours with, if applicable, a leading zero. 12-hour clock.
    • H: Hours. 24-hour clock.
    • HH: Hours with, if applicable, a leading zero. 24-hour clock.
    • m: Minutes.
    • mm: Minutes with, if applicable, a leading zero.
    • s: Seconds.
    • ss: Seconds with, if applicable, a leading zero.
    • l: Milliseconds.
    • t: Produces a single, lowercase character ("a" or "p") for ante meridiem and post meridiem.
    • tt: Produces a two, lowercase characters ("am" or "pm") for ante meridiem and post meridiem.
    • T: Produces a single, uppercase character ("A" or "P") for ante meridiem and post meridiem.
    • TT: Produces a two, uppercase characters ("AM" or "PM") for ante meridiem and post meridiem.
  • Default: Integer, Optional. Defaults to 0. Specifies which values to use as defaults for date parts which are not specified in the specified format.
    • 0: Default. Use JavaScript's default values (null). This will generally result in values at the beginning of the acceptable date range (for example January 1, 1899).
    • 1: Use the current date/time as default values.
    • 2: Use the current UTC date/time as default values.

Return

Date or Null. If the passed information can be converted to a date the method returns a native JavaScript date object. If not a null value is returned.

Date.parseIso8601()

This static method converts compliant ISO 8601 date strings into native JavaScript Date objects. The formats allowed are described in the Date and Time Formats W3C note.

Method Signature

Date.parseIso8601(Input)

Arguments

  • Input: String, Required. A string representing the date you wish to convert.

Return

Date or Null. If the passed information can be converted to a date the method returns a native JavaScript date object. If not a null value is returned.

Date.parseHttpTimeFormat()

This static conveinence method converts HTTP dates (specified in RFC 822) date strings into native JavaScript Date objects. Identical to Date.parseFormat(CurDate, "DDD, D MMM YYYY HH:mm:ss z").

Method Signature

Date.parseHttpTimeFormat(Input)

Arguments

  • Input: String, Required. A string representing the date you wish to convert.

Return

Date or Null. If the passed information can be converted to a date the method returns a native JavaScript date object. If not a null value is returned.

DateInstance.add()

Adds a specified number of the specified date units to the date.

Method Signature

DateInstance.add(Amount, DatePart, [Destructive])

Arguments

  • Amount: Integer, Required. The number of units by which to modify the date. Positive numbers will result in future dates; negative numbers will result in past dates.
  • DatePart: String, Required. The unit to add to the date. The following date parts are supported:
    • milliseconds: Milliseconds.
    • seconds: Seconds.
    • minutes: Minutes.
    • quarterhours: 15 minutes.
    • warhols: 15 minutes (of fame).
    • halfhours: 30 minutes.
    • hours: Hours.
    • days: Days.
    • weeks: Weeks (periods of 7 days).
    • businessdays: Days excluding Saturday and Sunday. Note that holidays are NOT considered.
    • businessweeks: Business weeks (periods of 5 business days).
    • wholeweeks: Weeks from Sunday to Saturday. Essentially the current date will be moved to the next Sunday, then the week(s) specified will be added.
    • months: Months. The date (day of month) may change (to the last day of the new month) if months have an incompatible number of days. For example adding one month to March 31 will result in April 30.
    • years: Years. If the date is February 29th (a leap year) it may be changed to February 28th if the resulting year is not a leap year.
  • Destructive: Boolean, Optional. Defaults to false. If false (the default) the method will return a new date object with the results; if true the method will update the date in place and return a reference to the original date.

Return

Date.

DateInstance.compare()

Does a comparison of two dates to an optionally specified precision.

Method Signature

DateInstance.compare(Date, [Precision])

Arguments

  • Date: Date, Required. The date to compare.
  • Precision: String, Optional. Defaults to "millisecond". Acceptable values are:
    • millisecond: (The default.) Comparison precise to the millisecond.
    • second: Comparison precise to the second.
    • minute: Comparison precise to the minute.
    • hour: Comparison precise to the hour.
    • day: Comparison precise to the day.
    • month: Comparison precise to the month.
    • year: Comparison precise to the year.

Return

Integer. The method returns zero ("0") if the dates are equal, negative one ("-1") if the original date falls prior to the passed date or positive one ("1") if the original date falls after the passed date.

DateInstance.dateFormat()

Method Signature

DateInstance.dateFormat(Mask)

Arguments

  • Mask: String, Required. The mask to apply to the date. The following case-sensitive mask values are supported:
    • D: The day of the month as a number.
    • DD: The day of the month as a number with, if applicable, a leading zero.
    • DDD: The day of the week as a three-character abbreviation (for example "Tue").
    • DDDD: The full name of the day of the week (for example "Tuesday").
    • M: The month as a number.
    • MM: The month as a number with, if applicable, a leading zero.
    • MMM: The month as a three-character abbreviation (for example "Jan").
    • MMMM: The full name of the month (for example "January").
    • YY: The last two digits of the year.
    • YYYY: The four-digit year.
    In addition the following case-sensitive short-hand values are also acceptable:
    • short: Identical to "M/D/YY".
    • medium: Identical to "MMM D, YYYY".
    • long: Identical to "MMMM D, YYYY".
    • full: Identical to "DDDD, MMMM D, YYYY".
    These short-hand values cannot be mixed with other mask values.

Return

String. The formatted date as described by the specified mask.

DateInstance.dayOfYear()

This function returns the ordinal day of the year.

Method Signature

DateInstance.dayOfYear()

Arguments

  • None.

Return

Integer. The day of year (1-366).

DateInstance.diff()

Returns the number of specified date units between two dates.

Method Signature

DateInstance.diff(Date, DatePart)

Arguments

  • Date: Date, Required. The date to calculate the difference from.
  • DatePart: String, Required. The kind of unit to count. The following date parts are supported:
    • milliseconds: Milliseconds.
    • seconds: Seconds.
    • minutes: Minutes.
    • quarterhours: 15 minutes.
    • warhols: 15 minutes (of fame).
    • halfhours: 30 minutes.
    • hours: Hours.
    • days: Days.
    • weeks: Weeks (periods of 7 days).
    • businessdays: Days excluding Saturday and Sunday. Note that holidays are NOT considered.
    • businessweeks: Business weeks (periods of 5 business days).
    • wholeweeks: Weeks from Sunday to Saturday. Only whole weeks will be counted.
    • months: Months.
    • years: Years.

Return

Integer. The number of whole units between the two dates (no fractions will be returned).

DateInstance.httpTimeFormat()

A convenience method which generates HTTP dates (specified in RFC 822) for output. For example "Sun, 13 May 2007 18:05:45 -0400".

Method Signature

DateInstance.httpTimeFormat(isUTC)

Arguments

  • isUTC: Boolean, Optional. Defaults to "false". Pass "true" if the datetime is UTC, "false" if the datetime is local time.

Return

String. An date formatted accorded to RFC 822.

DateInstance.isLeapYear()

Returns true if the datetime falls within a Leap Year.

Method Signature

DateInstance.isLeapYear()

Arguments

  • None.

Return

Boolean. True if the datetime is within a Leap Year, false if not.

DateInstance.isWeekday()

Returns true if the datetime falls on a weekday (monday through friday, inclusive).

Method Signature

DateInstance.isWeekday()

Arguments

  • None.

Return

Boolean. True if the datetime falls on a weekday, false if not.

DateInstance.iso8601Format()

A convenience method which generates ISO 8601 formatted dates for output.

Method Signature

DateInstance.iso8601Format(Style, [isUTC])

Arguments

  • Style: String, Optional. Defaults to "YMDHMSM". The style of the date to be output. Can be any of the following:
    • Y or 1: "Year". Equivalent to dateFormat("yyyy").
    • YM or 2: "Year and Month". Equivalent to dateFormat("yyyy-mm").
    • YMD or 3: "Year, Month and Day". Equivalent to dateFormat("yyyy-mm-dd").
    • YMDHM or 4: "Year, Month, Day, Hours and Minutes". Equivalent to dateFormat("yyyy-mm-dd") + "T" + timeFormat("HH:mm") plus timezone information.
    • YMDHMS or 5: "Year, Month, Day, Hours, Minutes and Seconds". Equivalent to dateFormat("yyyy-mm-dd") + "T" + timeFormat("HH:mm:ss") plus timezone information.
    • YMDHMSM or 6: "Year, Month, Day, Hours, Minutes, Seconds and Milliseconds". Equivalent to dateFormat("yyyy-mm-dd") + "T" + timeFormat("HH:mm:ss.l") plus timezone information.
  • isUTC: Boolean, Optional. Default to "false". Specifies if the date is to be treated as a UTC date or not. If "true" the UTC indicator will be appended to the dates with time values, if "false" timezone information will be appended to dates with time values.

Return

String. An ISO 8601 formatted date.

DateInstance.timeFormat()

Method Signature

DateInstance.timeFormat(Mask)

Arguments

  • Mask: String, Required. The mask to apply to the time. The following case-sensitive mask values are supported:
    • h: Hours. 12-hour clock.
    • hh: Hours with, if applicable, a leading zero. 12-hour clock.
    • H: Hours. 24-hour clock.
    • HH: Hours with, if applicable, a leading zero. 24-hour clock.
    • m: Minutes.
    • mm: Minutes with, if applicable, a leading zero.
    • s: Seconds.
    • ss: Seconds with, if applicable, a leading zero.
    • l: Milliseconds.
    • t: Produces a single, lowercase character ("a" or "p") for ante meridiem and post meridiem.
    • tt: Produces a two, lowercase characters ("am" or "pm") for ante meridiem and post meridiem.
    • T: Produces a single, uppercase character ("A" or "P") for ante meridiem and post meridiem.
    • TT: Produces a two, uppercase characters ("AM" or "PM") for ante meridiem and post meridiem.
    In addition the following case-sensitive short-hand values are also acceptable:
    • short: Identical to "h:mm tt".
    • medium: Identical to "h:mm:ss tt".
    • long: Identical to "h:mm:ss.l tt".
    • full: Identical to "long" (reserved).
    These short-hand values cannot be mixed with other mask values.

Return

String. The formatted date as described by the specified mask.

DateInstance.weekOfYear()

Returns the week of year on which the datetime falls, from 1 to 52.

Method Signature

DateInstance.weekOfYear()

Arguments

  • None.

Return

Integer. The week of the year.

Examples back to top

All of these examples assume that the library has been imported as noted in the usage section.

Parsing ISO 8601 Dates

To parse ISO 8601 dates invoke the parseIso8601() method directly from the data object. The following examples represent parsable versions of ISO 8601 dates:

  • MyFormattedDate = Date.parseIso8601("2006");
  • MyFormattedDate = Date.parseIso8601("2006-06");
  • MyFormattedDate = Date.parseIso8601("2006-06-21");
  • MyFormattedDate = Date.parseIso8601("2006-06-21T14:46");
  • MyFormattedDate = Date.parseIso8601("2006-06-21T14:46:34");
  • MyFormattedDate = Date.parseIso8601("2006-06-21T14:46:34.876");
  • MyFormattedDate = Date.parseIso8601("2006-06-21T14:46:34Z");
  • MyFormattedDate = Date.parseIso8601("2006-06-21T14:46:34-05:00");

Formatting Dates

Several examples of date formatting follow (these assume that "CurDate" is a valid JavaScript Date):

  • write(curDate.dateFormat("short");
  • write(curDate.dateFormat("full");
  • write(curDate.dateFormat("ddd, mm d, yyyy");
  • write(curDate.dateFormat("dddd, mmmm d, yyyy");
  • write(curDate.dateFormat("dd/mm/yy");

The above examples would result in the following:

Formating Times

Several examples of time formatting follow (these assume that "CurDate" is a valid JavaScript Date):

  • curDate.timeFormat("short");
  • curDate.timeFormat("medium");
  • curDate.timeFormat("HH:mm:ss");
  • curDate.timeFormat("h:mm:ss tt");
  • curDate.timeFormat("h:mm:ss.l tt");
  • curDate.timeFormat("h:mm TT");

The above examples would result in the following:

Generating ISO 8601 Date/Times

Several examples of ISO 8601 formatting follow (these assume that "CurDate" is a valid JavaScript Date):

  • curDate.iso8601Format("Y");
  • curDate.iso8601Format("YM");
  • curDate.iso8601Format("YMD");
  • curDate.iso8601Format("YMDHM");
  • curDate.iso8601Format("YMDHMS");
  • curDate.iso8601Format("YMDHMSM");
  • curDate.iso8601Format("YMDHM", true);
  • curDate.iso8601Format("YMDHMS", true);
  • curDate.iso8601Format("YMDHMSM", true);

The above examples would result in the following:

52 Current Sessions; Time: 16:22:02 23-07-2008; Tick: 1109