Date Creation in JavaScript

By Robert Gravelle

There aren't very many native date calculation functions in JavaScript other than a lot of setters and getters. From date parsing to formatting to calculations, you're pretty much on your own. And that can be a scary thought, because dates are notoriously difficult to work with. In today's article we're going to examine some date basics and how to create them in JavaScript.

The Date Object

As in most programming languages, JavaScript stores each date as an extremely large number, which holds the number of milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC). How large? To put it in perspective, one day contains 86,400,000 milliseconds! The Date object allows a range of plus or minus 100,000,000 days (or about 273,973 years in either direction) from 01/01/1970 (UTC). The Date's internal format is crucial to know because knowing how to convert between the string representation and the internal "real" date value is key to avoiding logic errors.

Creating a Date With JavaScript

JavaScript offers us no less than four ways to create a Date object. Each of the following constructors create a date as follows:

  • new Date(): using the local date and time.
  • new Date(milliseconds): using the supplied number of milliseconds since 01/01/70 00:00:00.
  • new Date(dateString): using the string parameter that represents the date in a format that is recognized by the Date.parse() method. (more on that in a bit). The local time zone is used to interpret arguments that do not contain time zone information. So, if you mean to create a date without a time portion, put one in with zeros (00:00).
  • new Date(year, month, day, hours, minutes, seconds, milliseconds): using supplied integers that represents the year, month, day, hours, minutes, seconds and milliseconds of the date.

Accepted dateString Formats

The Date.parse() and Date(dateString) constructor accept both RFC822 and ISO 8601 formatted date strings. Here is a run down of both:

The RFC822 standard specifies a syntax for text messages sent via email transmission. When the standard was codified in 1977, Request for Comments (RFC) #733, "Standard for the Format of ARPA Network Text Message", by Crocker, Vittal, Pogran, and Henderson replaced the Arpanet's several existing informal email standards. Here is the RFC822 Standard in a nutshell:

date-time   =  [ day "," ] date time        ; dd mm yyyy
                                            ;  hh:mm:ss zzz

day         =  "Mon"  / "Tue" /  "Wed"  / "Thu"
            /  "Fri"  / "Sat" /  "Sun"

date        =  1*2DIGIT month 2DIGIT        ; day month year
                                            ;  e.g. 20 Jun 82

month       =  "Jan"  /  "Feb" /  "Mar"  /  "Apr"
            /  "May"  /  "Jun" /  "Jul"  /  "Aug"
            /  "Sep"  /  "Oct" /  "Nov"  /  "Dec"

time        =  hour zone                    ; ANSI and Military

hour        =  2DIGIT ":" 2DIGIT [":" 2DIGIT]
                                            ; 00:00:00 - 23:59:59

zone        =  "UT"  / "GMT"                ; Universal Time
                                            ; North American : UT
            /  "EST" / "EDT"                ;  Eastern:  - 5/ - 4
            /  "CST" / "CDT"                ;  Central:  - 6/ - 5
            /  "MST" / "MDT"                ;  Mountain: - 7/ - 6
            /  "PST" / "PDT"                ;  Pacific:  - 8/ - 7
            /  1ALPHA                       ; Military: Z = UT;
                                            ;  A:-1; (J not used)
                                            ;  M:-12; N:+1; Y:+12
            / ( ("+" / "-") 4DIGIT )        ; Local differential
                                            ;  hours+min. (HHMM)

Examples of RFC822-formatted date strings include "Mon, 15 Aug 2005 15:52:01 EDT +0000", "'25 December, 2010 6:00:00 Am'" and "15 Aug 2005". Note that supplying a two digit year as in "Mon, 15 Aug 05 15:52:01" won't work in JavaScript!

The international ISO (ISO 8601) spec defines a format of "YYYY-MM-DD" which eliminates the ambiguities caused by the dd/mm/yy and mm/dd/yy formats. For example, using the international format, "3rd of April 2002" would be expressed as "2002-04-03".

One oddity about the JavaScript Date.parse() function is that it does not like the hyphen (-) date part delimiters. Therefore, you should replace them with forward slashes (/), as in "2005/06/13" rather than "2005-06-13".

Date constructors nor the Date.parse() function throw errors. Instead they result in a NaN value. We can use that to test a date's validity. Here's a function that can be applied to any string to determine whether or not it represents an acceptable date format:

String.prototype.isValidDate = function isValidDate() {
	return !isNaN(Date.parse(this));

Greenwich Mean Time versus Universal Time

Although JavaScript technically supports both Universal (UTC) time and Greenwich Mean Time (GMT), the toGMTString() function has been deprecated and has been replaced by toUTCString(). A little history will explain why.

As of the mid-nineteenth century, Greenwich Mean Time (GMT) had been established as the primary reference time zone for the British Empire and for much of the world. GMT is based on the line of longitude running through the Greenwich Observatory located in the suburbs of London. Over time, time zones became established based on GMT as being x number of hours ahead or behind GMT. The catalyst for a new international time standard was the Atomic clock, as its accuracy negated the need to keep time based on average solar time at a particular location. Moreover, more accurate time keeping also permitted accounting for the irregularity of the earth and the sun's movements, by occasionally modifying the time through the use of leap seconds. Although UTC was used since the beginning in the mid-twentieth century, it officially became the new standard of world time on January 1, 1972.



Now that we've covered the basics of Date creation, we'll be better equipped to perform calculations on dates such as converting between formats, matching between time intervals, determining time lapses, and adjusting for leap years. That of course, will be discussed shortly in an upcoming article.

About the Author

Rob Gravelle resides in Ottawa, Canada, and is the founder of Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses. Email Rob to receive a free estimate on your software project. Should you hire Rob and his firm, you'll receive 15% off for mentioning that you heard about it here!

In his spare time, Rob has become an accomplished guitar player, and has released several CDs. His former band, Ivory Knight, was rated as one Canada's top hard rock and metal groups by Brave Words magazine (issue #92). Please support Rob by taking a minute to visit iTunes and purchase one of Rob's songs.

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date