Tutorial Index
















Need Help?

WA's Ultimate JavaScript Tutorial

Lesson 7-Working with time

If you were like me, before I learned JavaScript, one of the most eager things I wanted to know was how to access the time using JavaScript-displaying it, working with it and so on. Well, it was, in fact very easy, and I'll tell you why. JavaScript already has a built in object that gets the date and time for you -all you have to do is use it! In this section, we'll take a look at:

The Date Object

To use this date object, you need to first create an instance of it. Uh? Instant noodles? Well, not quite. .What we have to do is tell JavaScript to activate this object. Why didn't we do so for the others, such as the "document", or "forms" object? Well, these, and most of the others, are automatically created whenever you load a webpage containing these attributes, such as text, forms, and images. But "date" is a little different. This is not a normal part of every webpage, so it is not created automatically. Hay, but don't worry, creating it is about as easy as using it.

To create a Date Object so you can use it:

var mydate= new Date()

Whenever you want to create an instance of the date object, or anyone of the ones that require you to do so, use this important word: new followed by the object name(). Now, I'm going to list some of the methods of the date object that you can use:

Some methods for the date object: (uses the time displayed on your cmpt)
getDate()   returns the day of the month
getDay()   Returns the day of the week
getHours()   returns the hour (Starts from 0-23)!
getMinutes()   returns the minutes
getSeconds()   returns the seconds
getMonth()   returns the month. (Starts from 0-11)!
getYear()   returns the year
getTime()   returns the complete time (in really weird format)

Ok, lets say we want to write out today's date:

var today_date= new Date()
var myyear=
today_date.getYear()
var mymonth=
today_date.getMonth()+1
var mytoday=
today_date.getDate()

document.write("Today's date is: ")
document.write(myyear+"/"+mymonth+"/"+mytoday)

output:

  • Come back tomorrow, and the date shown would be different.
  • Lets have a look at the codes in red. "today_date" is the instance of the date object, you could name it anything you want. After creating an instance, that instance can use all the methods. So:
    var myyear=today_date.getYear()
    means "get the year and put it in variable myyear."
  • We added "1" to the month, since in JavaScript, it counts months starting from "0", not "1".

Dynamically writing out html codes

With the above knowledge, and a little HTML, you can display different images according to the date/time. Here is a common example: Displaying a different image depending on whether it is mourning or night.

Lets first get two images: (One for mourning, one for night.)

 

var current= new Date()
var day_night=current.getHours()
if (day_night<=12)
document.write("<img src='day.gif'>")
else
document.write("<img src='night.gif'>")

Output:

There is one very important concept here:

  • Take a look at the part in red. What we have done here is dynamically written out the html code required to display an image (not to be mistaken with dynamic html). Here is where JavaScript becomes amazing. You don't have to hard code your html tags into your webpage-allow JavaScript to think and write it out for you. Notice that we used the "write" method to do so, with the html code enclosed in " " This is how we write html in JavaScript.
  • So basically, if its mourning (before noon), "day.gif" will be shown, and at night, "night.gif."
  • Don't you get mesmerized looking at that sunset picture?

What else can you do with this object? Plenty. How about a live clock? Well, that is really fairly easy to do, provided we know this very important function:

setTimeout function

setTimeout, a method of the window object, basically delays the execution of a function or statement until the specified time has passed. The basic syntax of this function is:

setTimeout("expression", delaytime)

"expression" is the function/statement you want delayed, and delaytime is the delay time, in milliseconds.

For example, this will output "Three seconds have gone!" after 3 seconds.


document.three.hi.value=""
//simply clears the text box
function talk()
{
setTimeout("document.three.hi.value='Three seconds have gone!'",3000)
}

<form name="three">
<input type="text" size="28">
<input type="button" value="Start" onClick="talk()">
</form>

Let's do a example that, by placing the setTimeout in a special position, continuously writes to a box, incrementally itself every second.


var c=0
document.go.timer.value=""
function
count()
{
document.go.timer.value=c
c=c+1
setTimeout("count()",1000)
}

<form name="go">
<input type="text" name="timer" size="12">
<input type="button" value="Start"
onClick="count()">
</form>

  • A very important point is that the setTimeout method executes count() after one second, but look at the place where setTimeout is placed-inside count()! This will execute everything within function count(), including setTimeout itself, every one second. Basically, this forces the function to loop back and start at the beginning everytime it encounters this method. If you don't get it, study it a little harder-you'll see it!

  • The above function will run forever, until you reload or leave. This is exactly the function we need to create a clock...since we need a function that will continuously update itself. This function is so important, because whenever you write something that needs continuous refreshment, all you have to do is put a setTimeout function inside another function and call it. Now, a little thought will tell us that we can control this function, if we want to, so that it does not run forever, namely, by putting it in a if-else-statement. Note that to get "1" second, we used "1000". (1 milisecond*1000) equals 1 second.

Using setTimeout, we can implement a live clock. Ok, now that we have all the tools, lets do an example of that:

And, like always, here's the complete date object:

Date object
Methods
getDate
getDay
getHours
getMinutes
getMonth
getSeconds
getTime
getTimezoneOffset
getYear
parse
setDate
setHours
setMinutes
setMonth
setSeconds
setTime
setYear
toGMTString
toLocaleString
toString
UTC
valueOf

Lets attempt to make a live clock than, shaw we?

Lesson 8