Tuesday, May 6, 2008

JavaScript Date Object

posted by Jonah Dempcy

In this article I will explore the use of the JavaScript date object and its methods. We won't be using any JavaScript libraries because the existing API is quite adequate, and most libraries don't really offer much in the way of extensions anyway.

Let's start with displaying the current time. You can do this by using the Date() constructor and calling the toString() method on it. If you have Firebug, open up the console and type this code:

var date = new Date();
date.toString();

You'll see that date.toString() evaluates to a string containing the current time in Greenwich Meridian Time (GMT). In my case, it is "Tue May 06 2008 16:06:39 GMT-0700 (Pacific Daylight Time)."

There are a number of other to methods available as well. You can paste these into the Firebug console to see what they evaluate to. I've put my example as a comment after each one:

  • date.toDateString(); // "Tue May 06 2008"
  • date.toGMTString(); // "Tue, 06 May 2008 23:06:39 GMT"
  • date.toLocaleDateString(); // "Tuesday, May 06, 2008"
  • date.toLocaleString(); // "Tuesday, May 06, 2008 4:06:39 PM"
  • date.toLocaleTimeString(); // "4:06:39 PM"

Practical Applications of the JavaScript Date Object

One of the most obvious applications of the date object is to display the current time, should you desire to do so. Oftentimes news websites will contain the day's date, and sometimes they have a clock as well. For example, see the BBC's homepage which displays the day's date and an analog-style clock done in Flash:

The BBC follows the format "Tuesday 6 May 2008" for example. Let's construct that using JavaScript:

function getFormattedDate(date) {
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var day = days[date.getDay()];

    var months = ["January", "February", "March", "April", "May", "June", 
                  "July", "August", "September", "November", "December"];
    var month = months[date.getMonth()];

    // Returns a string formatted like "Tuesday 6 May 2008"
    return day + " " + 
           date.getDate() + " " +
           month + " " + 
           date.getFullYear();
}

getFormattedDate(new Date());

You could also accomplish this with some RegEx hackery but I think this is cleaner, albeit a bit more verbose. The benefit of doing this with RegEx is that you can use one of the existing toString() methods, such as toLocaleString(), and then parse the data you need from there.

Actually, given that the data is delimited by commas, you could accomplish this simply by splitting the returned string without the use of RegEx. Doing it that way would avoid the need to tediously specify the names of all the days and the months.

Creating a Countdown Timer in JavaScript

Another use case for the JavaScript date object is to count down the time remaining until a certain date. This could be the launch of a new website or product, the cut-off time for a submission, or anything else that requires notification of the time remaining until a specific date and time.

On a website I previously worked on, Endless.com, there is a countdown timer in the banner that notifies the customer how long they have to order to get next day shipping. This is a fun idea because it adds a little pressure for the customer to make an impulse buy as the cutoff time comes closer. I've seen similar uses on other e-commerce sites and it adds a nice touch, for those sites which offer next-day shipping.

To do something like this, I imagine you'd need two functions, one to update the HTML with the correct date string (given a date object as input), and another, possibly anonymous function that is declared with a setInterval, which decrements the current time and calls the update function. Without writing the implementation details, I imagine it would look something like this:

function updateTimeRemaining(date) {
    // implementation details for parsing data from date object
    // and updating the DOM
}

window.onload = function() {
    var interval = setInterval(function() {
        updateTimeRemaining(new Date());
    }, 1000);
};

The updateTimeRemaining() function would need to be written to output the time remaining given a date object. I feel that there may be a better way to do this than creating a new Date() instance every second, however. Could we not use the same date object but decrement its time manually every second? In any case, this isn't a full-fledged solution at this point, just an outline of one possible solution.

What are your favorite uses of the JavaScript date object? Do you have other use cases that I've left out here? Please leave them in the comments and I may even devote a whole article to them. There is quite a bit you can do with date and time and I'm always on the lookout for new uses. Hopefully these short examples will get you thinking about how you can use the JavaScript date object on your site.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home