Today is


JavaScript Date Object

Date is a predefined class or object in Javascript. You can get the time as well as the date. Since Javascript runs on the client-side, it will display the client's date and time.

First step is you declare the Date object as follows.

var now = new Date();

then you write the date as follows.

document.write (now);

<script language='javascript'>

var now = new Date();

document.write(now);

document.write (now.getDate() +  "/" +now.getMonth() + "/" + now.getYear());

</script>

I am giving a sample date that is displayed in my system, for instance Tue Apr 12 16:17:15 UTC+0100 2005.

To format this date

document.write (now.getDate() +  "/" +now.getMonth() + "/" + now.getYear());

will display the date as  dd/mm/yyyy

document.write (now.getMonth() + "/" + now.getDate() +  "/" + now.getYear());

will display the date as  mm/dd/yyyy. Similarly you can replace "/" with "." or ":" as required.

You may want to format the date, like Tuesday 12, April 2005. For that we can construct an Array which displays the

<script language='javascript'>
var now = new Date();
var weekdays = 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");
document.write(weekdays[now.getDay()] + ", " + now.getDate() + " " + months[now.getMonth()] + "," + now.getYear());
</script>

Will Display the date as described above. Just paste this javascript code in your page at the place where you want the date to be displayed.

We will see how to insert a calendar in the next tutorial. You will also learn how to place the javascript code in an external file.


© 2005. All rights reserved.