Monday, November 28, 2005

Date Comparison in JavaScript

The Date class in JavaScript can also be used for date comparison, like if someone would want to take a date after today as input, they can put the Date class to use to perform a checking on the inputed date.

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:
var myDate = new Date;
The date object will automatically be assigned the current date and time as its initial value. We can easily override the component parts of the date by using the various methods available for manipulating dates.

For example, to set our date object to 15th April 2006 you can specify the following immediately after the above declaration:

myDate.setMonth(3); // January = 0

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:

var today = new Date;
if (myDate < today)
alert('today is before 16th April 2006');
alert('today is after 15th April 2006');

Note that since the time of setting the today object is after that of setting the myDate object we know that myDate will still be less than today on that date itself (as we have not changed the value held in any of the time portions of either object from that originally set).
Earlier I didn't posses in-depth knowledge of these in-built JavaScript, which no matter come in handy & also save you a lot of trouble. Hope this post helps someone.

PHP, DHTML, C, C++ and many more languages,for help visit Programming Fourm

No comments: