Previous page
BACK

Dates
(Much Ado about nothing!)

 

JavaScript Dates

In our opinion, the correct way to represent a date is just a number (the number of days after a pre-determined date, for example a Julian date as used in astronomy). The makers of JavaScript in their wisdom decided that dates should be immensely complex. We therefore have four different ways of making a date, and about twenty different methods associated with a date!

Making a Date object

As mentioned, there are apparently four ways:
  1. Date() - create a date containing the current date and time;
  2. Date(string) - use a string to make a date, where the string is in the format "month day, year hours:minutes:seconds"
    (The usual unreasonable American date format);
  3. Date(year, month, day) - where the year parameter is the non-Y2K-compliant value of 0..99.
  4. Date(year, month, day, hours, minutes, seconds) - perhaps the most reasonable of the lot!

Remember that because a date is an object, you must specify new when you create it, otherwise errors will inevitably result. An acceptable example is:

    luckyDay = new Date(2000, 9, 13);
    alert("Your lucky day is " + luckyDay);

A quick question - what day does the above represent? Full marks if you said the thirteenth of October (!) - JavaScript perhaps takes things a bit far and certainly sows a lot of confusion by counting months from zero as well! Note that if you say luckyDay.value you're out of luck - you'll get an undefined for your troubles!

Date methods

There are lots. Here they are:
Method What it does
getYear* What year is it?
getMonth What month?
getDate get day of month (getDay gives you the day of the week)!
getHours, getMinutes, getSeconds As you would expect..
getTime Snip out the time section
getTimeZoneOffset What is the time zone offset for this region (in minutes)
setYear*, setMonth, setDate, setHours, setMinutes, setSeconds all take an integer and set the appropriate part of the date, for example, setHours(11)
setTime set Time of date object
toGMTString* convert date to Greenwich mean time format
toLocaleString convert date to the format commonly used in the user's geographical region
UCT How many milliseconds have elapsed since midnight 1970-1-1 GMT? Redundant (and similar) is parse() which returns the number of milliseconds since midnight 1970-1-1 local time.
Items marked with a red asterisk* are now 'deprecated' - you use them at your own risk.

Needless to say, grown up date handling (conversion to and from Julian dates, and adding or subtracting a certain number of days) are conspicuously absent. You have to add your own.

Summary

As is usually the case with computer languages, the designers have done everything in their power to sow confusion. Let's just
go back to where we were!


Webpage author jvs@anaesthetist.com Last update: 2000-10-7