var current_time = new Date();A Date instance created the way above will contain the current date and time. If we want to put a specific date/time an object we can use constructors with arguments. These arguments can be like this:
var birthday = new Date("December 17, 1995 03:24:00");
We can also use integer values to assign date/time. They should be in the following order:
var birthday = new Date(1995, 11, 17, 3, 24, 00);
![]() |
Please notice that we used 11 for December, because month enumeration starts with zero. |
The Date object doesn't have many properties, but it does have quite a large number of methods we can use. You can find the complete list of all methods of the Date object in the official documentation. In this section we shortly discuss some of them. The most interesting methods for us would be methods that allows us to extract information from an instance of the Date object. These methods are:
Methods getHours(), getMinutes(), and getSeconds() extract information about hours, minutes, and seconds respectively. Please notice that hour information is stored in military format (0 to 23, no am/pm suffix):
Two methods getTime() and parse() do the similar job. Both of them return an integer value that contains the number of milliseconds since January the 1st 00:00.00. The difference between these methods is that method getTime() does it for an existing Date object:
and methods parse() takes a string argument containing a date a returns the number of milliseconds between the first of January 00:00.00: The number of milliseconds can be used to set a date-time in another Date variable using method setTime():
var somewhen = new Date();
somewhen.setTime( Date.parse("July 28, 1990 04:45"); );
Thus, combining together methods getTime() and setTime() we can easily compute the time difference
between two events:
Do not forget that due to the fact mentioned above we have to subtract
70 from number of years.
var start_time = new Date();and then once in a period of time take the current time, compute the difference, and display the difference in a desired format:
function display_time()
{
var current_time = new Date();
var time_spent = new Date();
time_spent.setTime( current_time.getTime() - start_time.getTime() );
var msg = time_spent.getHours() + ":" +
time_spent.getMinutes() + "." +
time_spent.getSeconds();
document.clockform.clocktext.value = msg;
}
We are using usual input text element to display time. In the function above clockform is
a name of the form containing the clock text element and clocktext in the name of the
element:
<fotm name=clockform> <input type=text name=clocktext value="0:00.00"> </form>
So far everything seems very simple, but now we need to think about the next question: how we are going
to start function display_time(). The problem here is that we need to execute this
function not once and not even twice, but many many times to actually make our clock look like clock, that
is we can not run it upon some user event (unless we make user click on a button once in a second
). If we make our function display_time()
recursively call itself, then our page won't be able to handle any other event permanently renewing the
clock. So, the question we need to know an answer for is "How to execute a function once a given
period of time?".
There are two methods of object Window that can help us with this problem. These methods are:
function display_time()
{
var current_time = new Date();
var time_spent = new Date();
...
document.clockform.clocktext.value = msg;
setTimeout("display_time()", 700);
}
...
setTimeout("display_time()", 700); // to execute for the first time
If we decide to use method setInterval(), then we don't even have to modify our function. All we need to do is to insert a line of code:
setInterval("display_time()", 700);
to set the time interval for executing the function display_time().
The real example that contains the code implementing ideas discussed
above is a little bit more complicated. The biggest difference we haven't talked about is the necessity to
take into consideration the time zone, which can be obtained with method
getTimezoneOffset().
The second problem is that we need to stop the timer or interval events and their handlers once we moved from the page to another page. Let's consider a simple example:
<html>
<body>
<script> setInterval("alert('Hello!')", 3000); </script>
</body>
</html>
A page like this will give a user an alert message every three
seconds and there is no way to get rid of this annoying thing until you go to another page or close the
browser. Thus, we need a tool to be able to stop timer events and clear their handlers. Methods of the object
Window
var tmout = setTimeout("display_something()", 100000);
...
clearTimeout(tmout);
or define the event handler for event unload for the element body:
<body onUnload="clearInterval(intrvl);">
...
<script>
var intrvl = setInterval("do_something()", 2000);
</script>
...
Now we will try to illustrate usage of the timer events with two examples.
...
This page has been moved. You will automatically be redirected to the new location in 7 seconds. If your
browser doesn't support JavaScript of you turned it off <a href="new_location/oldpage">click here</a>.
<script>
setTimeout("location.href='new_location/oldpage'", 7*1000);
</script>
...
<style>
.moving_line {
font-size: 150%;
color: blue;
border-top-style: double;
border-bottom-style: double;
border-right-style: none;
border-left-style: none;
text-align: center;
width: 100%;
}
</style>
An element input created with the style above is shown below:
To make the user believe that the line moves we will do the following:
" ** This input text element is created with the style above ** " "** This input text element is created with the style above ** " "* This input text element is created with the style above ** *" " This input text element is created with the style above ** **" "This input text element is created with the style above ** ** " "his input text element is created with the style above ** ** T"To implement this we will use method substring() of the String object. This method takes two integer arguments start_index and end_index and returns a substring of the string that uses the method. The substring starts at the start_index and ends, as you can guess, at end_index. Thus, the following code: takes 5 first characters out of the original string, adds them to the very end of the string, and displays the result. In the example instead of using alert() method we will display the string by assigning the result to the value of the text input element. The only thing we need now is to run code like the one above periodically and increase the value of start_position variable. That is, we need to create a function like this:
var start_position = 0;
var str = "*** This string should be moving ***";
function move_string()
{
var moving_str = str.substring(start_position, str.length) + str.substring(0, start_position);
document.moveform.movetext.value = moving_str;
start_position++;
if( start_position == str.length )
start_position = 0;
}
and make this function a handler of a timer event. That is, execute it using setInterval() method:
<script>
var timerRef = setInterval("move_string()", 200);
</script>
The following example contains the complete code and also adds some
features that use clearInterval() method to redefine speed of the line.