Title: Date, Time, and Timers
1 Date, Time, and Timers
2- In Chapter 4 we saw that the concepts of date and
time are embodied in JavaScript through the Date
object. We looked at some of the properties and
methods of the Date object, including the
following - The methods getDate(), getDay(), getMonth(),and
getFullyear() allow us to retrieve date values
from inside a Date object. - The setDate(), setMonthO,and setFullyear()
methods allow us to set the date values of an
existing Date object. - The getHours(), getMinutesO, getseconds(), and
getMilliseconds() methods retrieve the time
values in a Date object. - The setHoursO,setMinutesO,setseconds(),and
setMilliseconds() methods allow us to set time
values of an existing Date object. - One thing that we didnt cover in that chapter
was the idea that the time depends on your
location around the world. in this chapter well
be correcting that omission by looking at date
and time in relation to world time.
3- World Time
- The concept of now means the same point in time
everywhere in the world. However, when that point
in time is represented by numbers, those numbers
differ depending on where you are. What is needed
is a standard number to represent that moment in
time. This is achieved through Coordinated
Universal Time (UTC), which is an international
basis of civil and scientific time and was
implemented in 1964. It was previously known as
GMT (Greenwich Mean Time), and indeed at the time
000 UTC, it is midnight in Greenwich, London.
4- The support for UTC in JavaScript comes from a
number of methods of the Date object that are
similar to those we have already seen. For each
of the set date and get date type methods
weve seen so far, there is a UTC equivalent. For
example, whereas setHours () sets the local hour
in a Date object, setUTCHours () does the same
thing for UTC time. Well be looking at these
methods in more detail in the next section. - In addition, there are three more methods of the
Date object that involve world time. We have the
methods toUTCstring() and toLocalestring(), which
return the date and time stored in the Date
object as a string based on either UTC or local
time. Newer browsers, IF 5.5 and NN 6, also
have the additional methods toLocaleTimestring
() toTimestring () toLocaleDatestring () and
toDatestring (). - If we simply want to find out the difference in
minutes between the current locales time and
that of UTC time, we can use the
getTimezoneOffset() method. If the time zone is
behind UTC, such as in the United States, it will
return a positive number If the time zone is
ahead, such as in Australia or Japan, it will
return a negative number.
5- In the following code we use the
toLocalestring(), toUTCstring(),
getTimezoneOffset (), toLocaleTimestring(),
toTimestring(), toLocaleDatestring(), and
toDatestring() methods and write their values out
to the page.
6lt!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01
Transitional//EN http//www.w3.org/TR/html4/loos
e.dtdgt lthtmlgt ltheadgt lttitlegtexamplelt/titlegt ltscr
ipt language-Javascript type-text/javascriptgt
var localTime new Date() lt/scriptgt lt/headgt ltbo
dygt lth4gt UTC Time is ltscript language-JavaScript
type-text/javascriptgt document.write(localTime.toU
TCString()) lt/scriptgt lth4gt Local Time is ltscript
language-JavaScript type-text/javascriptgt document
write (localTime toLocaleString
()) lt/scriptgt lth4gt
7lth4gt Time Zone Offset is ltscript
language-JavaScript type-text/javascriptgt document
.write(localTime.getTimezoneOffset()) lt/scriptgt
lth4gt Using toLocalTimeString() gives ltscript
language-JavaScript type-text/javascriptgt if
(localTime toLocaleTimeString) document write
(localTime toLocaleTimeString ()) lt/scriptgt lth4
gt Using toTimeString() gives ltscript
language-JavaScript type-text/javascriptgt if
(localTime toTimeString) document write
(localTime toTimeString () lt/scriptgt lth4gt Using
toLocaleDateString() gives ltscript
language-JavaScript type-text/javascriptgt if
(localTime toLocaleDateString) document write
(localTime toLocaleDateString ()) lt/scriptgt
8- Using toDatestring() gives
- ltscript language-Javascript type-text/javascrip
tgt - if (localTime. toflatestring)
-
- document write (localTime. toflatestring())
-
- lt/scriptgt
- lt/bodygt
- lt/htmlgt
- Save this and load it into your browser
- What you see will, of course, depend on which
time zone your - computer is set to, but you should see
something like you will see - in the next page.
9(No Transcript)
10- How It Works
- So how does this work? in the script block at the
top of the page, we have just this one line - This creates a new Date object and initializes it
to the current date and time based on the client
computers clock. (Note that in fact the Date
object simply stores the number of milliseconds
between the date and time on your computers
clock and midnight UTC time on the 1st of January
1970.) - Within the body of the page we have seven more
script blocks that use the three world time
methods we looked at earlier Note that some of
them are enclosed in an if statement, for example
11- This checks to see if the browser supports that
method and only makes use of it if it does. Older
browsers dont support all of the date/time
methods so doing this prevents ugly errors. In
the following line - We write the string returned by the toUTCstring
() method to the page. This converts the date and
time stored inside the localTime Date object to
the equivalent UTC date and time. Then the line - Returns a string with the local date and time
value. Since this time is just based on the
users computers clock, the string returned by
this method will also adjust for daylight saving
time (as long as the clock adjusts for daylight
saving time).
12- Next, the code
- writes out the difference, in minutes, between
the local time zones time and that of UTC time. - You may notice in Figure 9-2 that the difference
between New York time and UTC time is written to
be240 minutes, or 4 hours. Yet, in the previous
table, we said that New York is 5 hours behind
UTC time. So what is happening? - Well, actually in New York on October 16th,
daylight saving hours are in use. During the
summer when its 800 p.m. in New York and 000
UTC time, it is 700 p.m. in New York and 000
UTC time in the winter Therefore, in the summer
the getTimezoneOffset () method will return 240,
while in the winter the getTimezoneOffset ()
method will return 300.
13(No Transcript)
14- The next two methods are toLocaleTimestring() and
toTimestringO,as follows - These are NN 6- and IF 5.5-only methods. They
display just the time part of the date/time held
in the Date object. The toLocaleTimestring ()
method displays the time as specified by the user
on his computer. The second method displays the
time but also gives an indication of time zone
(in the example, EST for Eastern Standard Time in
America).
15- The final two methods display the date part of
the date/time. The toLocaleDatestring () displays
the date in the format the user has specified on
his computer On Windows operating systems, this
is set in the regional settings of the PCs
Control Panel. However because it relies on the
users PC setup, the look of the date will vary
from computer to computer The toDatestring()
method displays the current date contained in the
PC date in a standard format.
16- Setting and Getting a Date Objects UTC Date and
Time - When we create a new Date object, we can either
initialize it with a value or let JavaScript set
it to the current date and time. Either way,
JavaScript assumes we are setting the local time
values. If we want to specify UTC time, we need
to use the setUTC type methods, such as
setUTCHours (). - The following are the seven methods for setting
UTC date and time - setUTCDate()
- setUTCFullYear ()
- setUTCHours()
- setUTCMilliseconds ()
- setUTcMinutes()
- setUTCMonth()
- setUTCSeconds()
17- The names pretty much give away exactly what each
of the methods does, so lets launch straight
into a simple example, which sets the UTC time.
These UTC methods were introduced in IE 4.0 and
NN 4.06, so you will need one of these or a later
version to run the code.
18- You might want to change your computers time
zone and time of year to see how it varies in
different regions and with daylight saving
changes. For example, although Im in the U.K., 1
have changed the settings on my computer for this
example to Eastern Standard Time in the U.S.A. In
Windows you can make the changes by opening the
Control Panel and then double-clicking the
Date/Time icon.
19- For getting UTC dates and times, we have the same
functions as used for setting UTC dates and
times, except that this time, for example, its
getUTCHours () not setUTCHours (). - getUTCDate()
- getUTCDay()
- getUTCFullYear ()
- getUTCIHours()
- getUTCMilliseconds ()
- getUTCMinutes()
- getUTCMonth()
- getUTCSeconds()
- Notice that this time there is an additional
method, getUTCDay () . This works in the same way
as the getDay () method and returns the day of
the week as a number, from 0 for Sunday to 6 for
Saturday. - Because the day of the week is decided by the day
of the month, the month, and the year, there is
no setUTCDay () method.
20- The world time converter consists of two pages.
The first is a frameset page, and the second is
the page where the time conversion form exists.
Lets start by creating the frameset page. - This simply divides the page into two frames.
However, by setting the border between the frames
to 0, we can make it look like just a single
page. Save this frameset page as
WorldTimeConverterFrameset.htm - The left frame will contain the form in which the
user can select the city that she wants the time
of, and the right frame will show the results of
the conversion. The right frame will be written
using code, so there is no page to create for
that.
21(No Transcript)
22(No Transcript)
23(No Transcript)
24(No Transcript)
25- How It Works
- Before we look at WorldTimeConverter.htm, lets
just pick up on one point in the
frameset-defining page WorldTimeConverterFrameset.
htm. - Now well turn to the page WorldTimeConverter.htm
where most of the action is. In the body of the
page is a form in which weve defined a list box
using a ltselectgt element.
26- Each of the options displays the citys name in
the list box and has its value set to the
difference in minutes between that citys time
zone (in winter) and UTC. So London, which is the
same as UTC time, has a value of 0. Paris, which
is an hour ahead of UTC, has a value of 60 (that
is, 60 minutes). New York, which is 5 hours
behind UTC time, has a value of -300. - Youll see that we have captured the onchange
event of the ltselectgt element and connected it to
the function updateTimeZone () defined in a
script block in the head of the page. This
function involves three global variables defined
at the top of the script block. - The function updateTimezone() updates two of
these, setting the variable timeDiff to the value
of the lists selected option (that is, the time
difference between the selected city and UTC
time) and the variable selectedCity to the text
shown for the selected option (that is, the
selected city).
27- in the final part of the function updateTimeZone
() the function updateTime () is called as shown
in the following - Before we go on to look at this function, we
return to the final part of the form on the page.
This is a checkbox, which is clicked by the user
if the city she has chosen from the select list
is in the summertime of a country that uses
daylight saving hours. - As you can see, this checkboxs onc lick event is
connected to another function, chkDaylightsaving_o
nclick ().
28- Inside the if statement, the code accesses the
checkboxs checked property, which returns true
if it is checked and false otherwise. if it has
been checked, we set the global variable
daylightsavingAdjust to 60 for summertime
daylight saving otherwise its set to 0. - At the end of this function (as at the end of the
function updateTimeZone () we saw earlier), the
updateTime() function is called. Well look at
that next. - In the function updateTime ( ), we write the
current local time and the equivalent time in the
selected city to the right-hand frame, named
resultsFrame, which we defined in the frameset
page.
29- We start at the top of the function by creating a
new Date object, which is stored in the variable
nowTime. The Date object will be initialized to
the current local time. - Next, to make our code more compact and easier to
understand, we define a variable resultsFrame,
which will reference the document object
contained in the resultsFrame window. - With our reference to the resultsFrame document,
we then open the document to write to it. Doing
this will clear anything currently in the
document and provide a nice blank document to
write our HTML into. The first thing we write is
the local time based on the new Date object we
just created. However, we want the time to be
nicely formatted as hoursminutesseconds, so
weve written another function, getTimeString ( )
, which does this for us. Well look at that
shortly.
30- Having written the current time to our
resultsFrame, we now need to calculate what the
time would be in the selected city before also
writing that to the resultsFrame. - We saw in Chapter 4 that if we set the value of a
Date objects individual parts (such as hours,
minutes, and seconds) to a value beyond their
normal range, JavaScript assumes you want to
adjust the date, hours, or minutes to take
account of this. For example, if we set the hours
to 36, JavaScript simply sets the hours to 12 and
adds one day to the date stored inside the Date
object. We use this to our benefit in the
following line - First we get the minutes of the current local
time its 511, so nowTime.getMinutes() returns
11.Then we get the difference, in minutes,
between the users local time and UTC time using
nowTime.getTimezoneOffset () . if we are in New
York, which is different from UTC time by 4 hours
during the summer, this is 240 minutes.
31- Then we get the integer value of the time
difference between the standard winter time in
the selected city and UTC time, which is stored
in the variable timeDiff. Weve used parselnt ()
here because its one of the few situations where
JavaScript gets confused and assumes we want to
join two strings together rather than treat the
value as a number and add it together Remember
that we got timeDiff from an HTML elements
value, and an HTML elements values are strings,
even when they hold characters that are digits.
Since we want the time in Berlin, which is 60
minutes different from UTC time, this will be 60. - Finally, we add the value of daylightsavingsAdjust
. This variable is set in the function
chkdaylightsavingonclick ( ) , which we discussed
earlier Since we are in the summer and Berlin
uses daylight saving hours, this value is 60. - So we have the following
- 11 240 60 60 - 371
32- Therefore nowTime. setMinutes () is setting the
minutes to 371. Clearly, theres no such thing as
371 minutes past the hour, so instead JavaScript
assumes we mean 6 hours and 11 minutes after
500, that is 1111the time in Berlin that we
wanted. - Finally the updateTime () function writes the
results to the resultsFrame, then closes off the
document writing. - In the updateTime () function, we saw that it
utilizes the function getTimeString () to format
the time string. Lets look at that function now.
This function is passed a Date object as a
parameter and uses that to create a string with
the format hoursminutesseconds.
33- The function therefore gets the values for hours,
minutes, and seconds and checks each to see if
they are below 10. If they are below 10, a zero
is added to the front of the string. When all the
values have been retrieved, they are concatenated
together in the variable timestring before being
returned to the calling function.
34- Timers in a Web Page
- We can create two types of timers in IF 4.0 and
NN 4.0 browsers. The one-shot tinier triggers
just once after a certain period of time, and the
second type of timer continually triggers at set
intervals. We will investigate each of these
types of timers in the next two sections. Note
that the first type, the one-shot timer, is the
only one available in older browsers supporting
JavaScript. - Within reasonable limits we can have as many
timers as we want and can set them going at any
point in our code, such as at the window onload
event or at the click of a button. Common uses
for timers include advertisement banner pictures
that change at regular intervals or display the
changing time in a web page. Also all sorts of
animation done with DHTML need setTimeout () or
setlnterval () well be looking at DHTML later on
in the book.
35- One-Shot Timer
- Setting a one-shot timer is very easy we just
use the window objects setTimeout () method. - The method setTimeout () takes two parameters.
The first is the JavaScript code we want
executed, and the second is the delay, in
milliseconds (thousandths of a second), until the
code is executed. - The method returns a value (an integer), which is
the timers unique ID. if we decide later that we
want to stop the timer firing, we use this ID to
tell JavaScript which timer we are referring to.
36(No Transcript)
37- Save this file as timertes.htm, and load it into
your browser In this page a message box will
appear 3,000 milliseconds (that is 3 seconds)
after the on load event of the window has fired. - Although setTimeout () is a method of the window
object, youll remember that because the window
object is at the top of the hierarchy, we dont
need to use its name when referring to its
properties and methods. Hence, we can use
setTimeout () instead of window. setTimeout() - Its important to note that setting a timer does
not stop script from continuing to execute. The
timer runs in the background and fires when its
time is up. In the meantime the page runs as
normal, and any script after we start the timers
countdown will run immediately. So, in this
example, the alert box telling us that the timer
has been set appears immediately after the code
setting the timer has been executed. - How about if we decided that we wanted to stop
the timer before it fired?
38- To clear a timer we use the window objects
clearTimeout () method. This takes just one
parameter, the unique timer ID that the
setTimeout () method returns.
39(No Transcript)
40(No Transcript)
41- Once youve typed in the code, save the page as
Adverts .htm. Youll also need to create three
images named Advert Imagel. jpg, Advert Image2 .
jpg, and Advert Image3 . jpg (alternatively, the
three images are supplied with the downloadable
code for the book). - When the page is loaded, we start with a view of
Advertlmagel. jpg, as shown bellow. - in three seconds this changes to the second
image, as shown in Figure 9-6. - Finally, three seconds later, a third and final
image loads, as shown in bellow.
42- Setting a Timer that Fires at Regular Intervals
- The introduction of
- The introduction of IF and NN version 4 browsers
saw new methods added to the window object for
setting timers, namely the setlnterval () and
clearlnterval () methods. These work in a very
similar way to setTimeout() and clearTimeout (
), except that the timer fires continually at
regular intervals rather than just once. - The method setlnterval() takes the same
parameters as setTimeout (),except that the
second parameter now specifies the interval, in
milliseconds, between each firing of the timer,
rather than just the length of time before the
timer fires. - For example, to set a timer that will fire the
function myFunction () every 5 seconds, the code
would be as follows - As with setTimeout ( ), the setlnterval () method
returns a unique timer ID that youll need if you
want to clear the timer with clearlnterval
(),which works identically to clearTimeout ( ) .
So to stop the timer started above, we would use
the following
43- Lets change the world time example that we saw
earlier, so that it displays local time and
selected city time as a continuously updating
clock. - Well be making changes to the WorldTimeconverter.
htm file, so open that in your text editor. Add
the following function before the functions that
are already defined - Next edit the ltbodygt tag so it looks like this
44(No Transcript)
45- Save the page as scrolling status. htm and load
it into your browser in the status bar at the
bottom of the browsers window, youll see this
scrolling message Beginning JavaScript from Wrox
Press.
46- How It Works
- At the top of the script block we define three
global variables, as follows - The message we want scrolled in the status bar is
stored in the variable message. The variable
startChar will later be used to determine the
portion of the message to be displayed in the
scroll bar and will help give the impression of
text scrolling from the right and disappearing
off to the left. The variable maxLength will
later store the length of the string to be
displayed. - When the message first appears in the status bar,
we want it to appear approximately in the middle
as shown in Figure 9-8.
47- To achieve this, we need to pad the front of the
message with enough spaces so that it will be
approximately in the middle. Otherwise, the
message will start being displayed at the left of
the status bar. The question is how many spaces
do we need? This will depend to some extent on
the users screen resolution and how wide his
browser window is. We deal with this in the
window on load () function that is connected to
the window objects onload event in the ltbodygt
tag for the page. We find out how many pixels
wide the browser window is and then divide that
by ten to give us a very rough guide to the
number of spaces required.
48- Having calculated how many spaces we want, we
then use a while loop to create a string
containing that number of spaces and store it in
the variable spaces. - This variable is then concatenated to the front
of our message stored in variable message.
49- Now that we have our padded message string inside
the variable message, we want to make the text
look like it is scrolling to the left as shown in
Figures 9-9 and 9-10.
50- So how can this scrollMeasage() function make the
message move to the left by one character? This
is achieved simply by only showing part of the
message string. initially, all of the message
string is shown, that is, from character position
0 to maxLength. When the function is next called,
only the portion of the string from character
position 1 to maxLength is shown. And the next
time the function is called, only the portion of
the string from character position 2 to maxLength
is called. - Eventually all the spaces and most of the words
will not be displayed in the status bar, and it
will look as if our message has rolled off the
left-hand edge. - Once we display just an empty string in the
status bar, we start once more by displaying the
whole string again. Now we know the principle of
how it works, lets look at the following code
51- The first thing we do is put our message string
into the status bar However we dont put the
whole string in, but instead, using the substring
() method, we insert only part of it, the part
starting from the character position in the
variable startChar and ending with the last
character Remember that with substring () if we
dont pass a second parameter with the last
character index we want displayed, then we get
all the string from the start character to the
end. - When the page is first loaded startChar is 0, so
our substring will be everything from the first
character to the end of the string, or in other
words, the whole string. The variable startChar
is incremented within the function, so the next
time the function is called by the timer,
startChar will be 1, so our sub- string will
start from the second character. With each call
of the function, the start position gets further
along the string, which means that when displayed
in the status bar, it appears to the user that
the text is moving closer and closer to the left
of the window. - Eventually no characters will be displayed in the
status bar This occurs when startChar is the same
as the length of the string. Once this point is
reached, we need to reset the startChar variable
back to zero, giving the appearance of the text
starting to scroll from the middle of the status
bar again. We do this in the if statement at the
end of the function.