Dates

Dates are stored as the number of milliseconds from the Epoch 1 January 1970

 

To get the current date & time:

var today = new Date();

 

To set a date:

var special = new Date(1941, 1, 14);  //year, month (zero based!), day

 

Or even more precisely to the second:

var happy = new Date(1969, 10, 18, 11, 45, 23);  //year, month (zero based!), day, hours, minutes, seconds

 

 

Date object methods

 

today.getTime(); // returns the number of milliseconds since 01.01.1970

today.getDay(); // returns 0 - 6 day of week, where 0 = Sunday

today.getDate(); // returns 1 - 31 day of month

today.getMonth(); // returns 0 - 11

today.getFullYear() // returns YYYY, not zero based

today.getHours(); // returns 0 - 23

 

Example:

var today = new Date(1969, 10, 18);

today.getDay() ; //returns 2, indicating Tuesday

 

today.setMonth(2) ; // sets the month to March

today.setFullYear(1980) ; // sets year to 1980

today.setDay(0); // sets day to Sunday

 

 

Comparing Dates

 

var date1 = new Date(1969, 10, 18);

var date2 = new Date(1969, 10, 18);

 

if ( date1 == date2) { //returns false, because they are not the same OBJECT

 

if ( date1.getTime() == date2.getTime()) { //returns true, because the .getTime() method returns the milliseconds

Leave a Reply