JavaScript Date Object



Date Object

We have an in-built Date object in javascript which is used to display the current date-time of the system.
Date object is useful in cookies too, it is used to set the expiry date of the cookies.
Note:This date is of the computer of the user and not of the webserver.

Creating Instance of Date Object

To use the methods of Date object we have to first create an instance of the object.For this a keyword new
is used.

<html>
<head>
<script type="text/javascript">
var today=new Date();
document.write("Current date is:"+ today);
</script>
</head>
</html>




The variable "today" holds an instance to Date object.You can use it to call the methods such as getDate(),
getMonth() etc.
Note:new Date() calls the Date() contructor.
There are 4 ways of intantiating a Date object.

new Date() //gives current date and time
new Date(date string)
new Date(milliseconds)
new Date(year,month,day,hours,minutes,seconds,milliseconds)

d1=new Date();
d2=new Date("August 30, 2011 12:25:00");
d3=new Date(2011,7,11);
d4=new Date(2011,7,31,1,45,55);

Date Object Methods

There are various methods or functions of the Date Object.We use these methods
to print out the various information needed.

Method Description
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
toDateString() Converts the date portion of a Date object into a readable string
toUTCString() Returns the date according to Universal time.

Examples of Date Object

Using getMonth()

<html>
<head>
<script type="text/javascript">
var d=new Date();
var month=new array("january","february","march","april","may","june",
"july","august","september","october","november","december");
document.write("This Month is "+ month(d.getMonth()));
</script>
</head>
</html>



Using getDay()

<html>
<head>
<script type="text/javascript">
var d=new Date();
var day=["sun","mon","tue","wed","thurs","fri","sat"]
document.write("today is "+ day[d.getDay()]);
</script>
</head>
</html>



Using getFullYear()

<html>
<head>
<script type="text/javascript">
var year=new Date();
document.write("Year is "+ year.getFullYear());
</script>
</head>
</html>




Using toUTCString

<html>
<head>
<script type="text/javascript">
var str=new Date();
document.write("Universal time- "+ str.toUTCString());
</script>
</head>
</html>




Using toDateString()

<html>
<head>
<script type="text/javascript">
var today=new Date();
document.write("Date is- "+ today.toDateString());
</script>
</head>
</html>