Javascript | The Date Object
Next

The Date Object



The above piece of information is brought to you by the following Javascript snippet:

 
 
  var right_now = new Date(); 
  document.writeln("Todays's date is: " + 
     right_now + ".<br>");    

In this section of code right_now = new Date() creates a date object named right_now, which is then printed with document.writeln.

Getting the Time via a Link

What time is it now? (Move the mouse over the link several times and note that the date and time stay the same as printed above.)

This example uses:
 
What time is it <A HREF=""  
  onMouseOver="window.status='The time is ' + 
    right_now; return true;">now</a>? 

Notes:

  1. As above, the present date is gotten from right_now = new Date(); but this happens only once, when the page is loaded, so the value of right_now is not updated.
  2. When you move the mouse over the link, the value of right_now is displayed (but since this value is only defined once, the time is not updated).

And what time is it now? (Move the mouse over the link several times and note that here the time does change.)

The Javascript code in this case is
 
 
  function what_time() { 
  var now_is = new Date(); 
  window.status='The time is ' + now_is; 
  } 
 
  And what time is it  
  <A HREF="" onMouseOver="what_time(); 
    return true;">now</a>? 

Notes:

  1. Moving the mouse over the "now" link causes the user-defined function what_time() to be called. This sets now_is = new Date() to the current time and displays it on the status bar.
  2. Since what_time() is called each time the mouse is placed over the "now" link, the now_is variable is updated each time. Consequently the present date and time are shown.

You can extract parts of a date object by using its various methods. The following methods return the indicated date parts:

  • getDay() -- day of the week (a number between 0 -- 6)
  • getMonth() -- month of the year (a number between 0 -- 11)
  • getDate() -- day of the month (a number between 1 -- 31)
  • getHours() -- hour of the day (a number between 0 --23)
  • getMinutes() -- minutes after the hour (a number between 0 --59)
  • getSeconds() -- (a number between 0 --59)
  • getYear() -- the last two digits of the year

Finally, you can even have Javascript add a calendar to your page.

Next