Tripod
Tripod

   handcrafted

Vol. 2, No. 6
Doing Time With JavaScript


Long before we humans tamed fire or learned to make rudimentary yet modish garments from animal pelts, we had a notion of time. Hunt during the day; sleep at night. Sleep out under the moon during warm-season; sleep in the cave during cold-season. As civilization advanced, so did our understanding of time: time to plant, time to harvest; time to initiate the young men into adulthood. Time to honor the sun deity; time to bring in the herds; time to launder the rudimentary garments. And so forth, with modern innovations like wedding anniversaries, teatime, the theory of relativity, overtime, and the Date object in JavaScript. It's that last one that we're going to be discussing today.

The Date object is how JavaScript handles times and dates. The syntax to create a new date object is simple. Here's how it works.

var now = new Date();

That line initializes the variable "now" as an instance of the Date object, and stores the time and date -- at the moment the line is executed -- in the variable; so "now" is set equal to, say, "Thu Mar 08 14:48:49 GMT-0500 (EST) 2001". (The actual format of this date-and-time string varies somewhat from browser to browser and platform to platform.) The value of the variable won't tick along and keep up with us; it will just keep the value assigned to it until you tell it to change.

Alternately, you can create a date object with a specific date and time assigned to it other than the present moment, like so:

var davesbirthday = new Date(1966,2,26);

which results in the date "Sat Feb 26 00:00:00 GMT-0500 (EST) 1966". Notice that, since the time wasn't specified, that defaults to zero. You can include an exact time as well if you prefer:

var exactbirthday = new Date(1966,2,26,10,22,35);

which gives us "Sat Feb 26 10:22:35 GMT-0500 (EST) 1966".

So, in short, the format to use when assigning a new date object, as you may have guessed, is "new Date(year, month, day, hour, minute, second)".

Here is a little sample script that displays the current time in a form field whenever you click a button.

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
var now;
function showTime() {
  now = new Date();
  document.form.timeform.value = now.toString();
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="timeform">
<INPUT TYPE="TEXT" NAME="time" SIZE="50">

<INPUT TYPE="BUTTON" VALUE="What time is it?" onClick="showTime()"> </FORM> </BODY> </HTML>

[See it in action!]

What's happening here? Well, every time that button is clicked, it calls the showTime() function. That function, very simply, assigns the current date and time to the variable "now", and then displays the value of the variable in the form field on the page.

Now, that's kind of a clumsy excuse for a clock. One thing we like our clocks to do is to run by themselves, without the need for constant winding, clicking, or other types of hand-holding. We can use the setTimeout() method to make our clock tick along without human intervention.

The setTimeout() method, in case you've forgotten, does something at a certain defined interval. It takes two arguments: the thing to do, and the number of milliseconds before it does it. In the following script, we want to call the showTime() function every second (which equals 1000 milliseconds) -- automatically, rather than calling it by clicking a button. And we place the setTimeout() command within the function that's called by the command, so that once it's set in motion, it keeps on calling itself, and looping forever, updating the date object every 1000 milliseconds. Cool.

<FORM NAME="timeform">
<INPUT TYPE="TEXT" NAME="time" SIZE="50">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
<!--
var now;
function showTime() {
  now = new Date();
  document.timeform.time.value = now.toString();
  setTimeout('showTime()',1000);
}
showTime();
// -->
</SCRIPT>

[See it in action!]

The only problem now is the ugly format of the string. Who wants to have to contend with "Thu Mar 08 14:48:49 GMT-0500 (EST) 2001" when you just want to know the time of day? It's easy to extract individual elements of the date and time and format them however you want, by using the convenient methods that the Date object provides. Those methods include: getTime, getDate, getHours, getMinutes, getSeconds, getDay, getMonth, getYear, and getTimezoneOffset.

So. If we want to display just the hour and the minutes, we can do something like this:

var now = new Date();
var timedisplay = now.getHours() + '\:' + now.getMinutes();

Now, as a special bonus offer just for you, here's some cut-and-pastable code that translates a Date object date into a user-friendly format like "Saturday, February 26, 1966."

var days = new Array ('Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday');
var months = new Array ('January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October', 'November',
'December');
var theday = now.getDay();
var themonth = now.getMonth();
var datedisplay = days[theday] + ', ' + months[themonth] + ' ' +
now.getDate() + ', ' + now.getYear();

All it involves is setting up a couple of arrays of the proper names of the days and months, and then translating the numerical value returned by the Date object into the appropriate name.

That's about all there is to getting and displaying the time and date. Enjoy your newfound powers, and use them for good, never for evil.

RESOURCES:

Webmonkey's JavaScript tutorial

JavaScript reserved words

 
Subscribe/Unsubscribe

Handcrafted Archive

2002 March
February
January
2001 December
November
October
September
August
July
June
May
April
March
February
January
2000 December
November
October
September
August
July
June
May
April
March
February
January
1999 December
November
October
September
August
July
June
May
April
March
February



    Tripod: Home | Site Map | About Tripod | International | Tripod Help | Report Tripod Abuse | Members | Angelfire Members

     » Lycos.com  © Copyright 2009, Lycos, Inc. Lycos is a registered trademark of Lycos, Inc. All Rights Reserved.
     About Lycos | Help | Jobs | Advertise

     Your use of this website constitutes acceptance of the Lycos Privacy Policy and Terms & Conditions