Sei sulla pagina 1di 2

JavaScript Date Object

The Date object is used to work with dates and times.


Try it Yourself - !amples
"eturn today#s date and time
$ow to use the Date%& method to 'et today#s date.
'etTime%&
(se 'etTime%& to calculate the years since )*+,.
set-ullYear%&
$ow to use set-ullYear%& to set a specific date.
to(T.Strin'%&
$ow to use to(T.Strin'%& to convert today#s date %accordin' to (T.& to a strin'.
'etDay%&
(se 'etDay%& and an array to write a weekday/ and not just a number.
Display a clock
$ow to display a clock on your web pa'e.
.omplete Date Object "eference
-or a complete reference of all the properties and methods that can be used with the Date object/
'o to our complete Date object reference.
The reference contains a brief description and e!amples of use for each property and method0
.reate a Date Object
The Date object is used to work with dates and times.
The followin' code create a Date object called myDate1
var myDate=new Date()
Note: The Date object will automatically hold the current date and time as its initial value0
Set Dates
2e can easily manipulate the date by usin' the methods available for the Date object.
3n the e!ample below we set a Date object to a specific date %)4th January 5,),&1
var myDate=new Date();
myDate.setFullYear(2010,0,14);
6nd in the followin' e!ample we set a Date object to be 7 days into the future1
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
Note: 3f addin' five days to a date shifts the month or year/ the chan'es are handled automatically
by the Date object itself0
.ompare Two Dates
The Date object is also used to compare two dates.
The followin' e!ample compares today#s date with the )4th January 5,),1
var myDate=new Date();
myDate.setFullYear(2010,0,14);
var today = new Date();
! (myDate"today)
#
alert($%oday s &e!ore 14t' (anuary 2010$);
)
else
#
alert($%oday s a!ter 14t' (anuary 2010$);
)

Potrebbero piacerti anche