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.

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()

Using getDay()

Using getFullYear()

Using toUTCString

Using toDateString()

Comments on this entry are closed.