Introduction
The Date class in JavaScript.This class not only makes the manipulation of dates easier (regardless of which date format you prefer) but it also handles time as well.
Any time that you have a javascript that is required to do any sort of processing based on either the current date and time or which involves the comparison of two dates or times then using the Date class will make that processing much simpler.
Defining Dates
To be able to use the Date class we need to define objects of that type. To do this we use a command very similar to that which we used to define arrays.
The way to define an object as a date is like this:
Code: JavaScript
var myDate = new Date;
For example, to set our date object to 15th April 2006 you can specify the following immediately after the above declaration:
Code: JavaScript
myDate.setDate(15);
myDate.setMonth(3); // January = 0
myDate.setFullYear(2006);
Comparing Dates
One of the most useful areas where using the date class is useful is where you need to either compare two dates or to change a date or time by a specified amount. For example let's say that we want to compare today's date with the 15th April 2006. Is today before or after that date? To do this we need to add the following code to what we have already defined above:
Code: JavaScript
var today = new Date;
if (myDate < today)
alert('today is before 16th April 2006');
else
alert('today is after 15th April 2006');
Changing Dates
As well as comparing dates we can also easily manipulate dates. For example say that we need to work with the date exactly one week in the future All we need to do with a date object is to add 7 to the days portion of the date like this:
Code: JavaScript
myDate.setDate(myDate.getDate()+7);