Mastering JavaScript Dates: Introduction - Doc JavaScript | WebReference

Mastering JavaScript Dates: Introduction - Doc JavaScript

Mastering JavaScript Dates

If you've been surfing lately, you've probably noticed that many sites display the current date. Some do that in the form of an image, whereas others display the date as plain ASCII text. There are four ways to display the current date, each with its own pros and cons:

  1. Update the current date manually, every day. If you already update your site on a daily basis, this shouldn't be much of a problem.
  2. Setup a cronjob to update your site automatically at midnight. The easiest way to do this is to create a Perl script that manipulates your HTML document. Type man 5 crontab at a Unix command prompt for more information on cronjobs, or continue reading this column for detailed instructions.
  3. Use a server-side include to execute a CGI program that prints the date in the desired format. The CGI program is executed once for each page request (HTTP request), so this method can be resource-demanding.
  4. Last but definitely not least, you can write a short JavaScript script that displays the current date. This technique differs from the rest in that the date is extracted from the client, not from the server.

In this column we'll show you how to use JavaScript to display the date. Most importantly, we'll explain how to make the script compatible with all JavaScript-enabled browsers, including Navigator 2.0 and Internet Explorer 3.0. You'll find out:

  1. How to create an instance of the Date object.
  2. How to extract the desired properties from that instance.
  3. How to display the date in a good-looking format.
  4. How to setup a cronjob to set the date.
  5. How to implement a server-side include to do the job.

Created: September 11, 1997
Revised: April 12, 2000