Dates in JavaScript can be confusing at first but are fairly easy eventually.
Getting the current date
To create a new date:
var currentDate=new Date();
Create an alert to show currentDate and you will see the format. It looks hard to manipulate but it is not:
var currentFullDate=new Date();
var currentDate=currentFullDate.getDate();
The method getDate extracts just the numeric date (day of the month) from the date. You can extract any other part in the same way by changing the bit after "get" (e.g. getDay, getYear, getMinutes and even getTimezoneOffset).
Other dates
You can also manually fix the date:
var myDate=new Date('January 16, 1988');
JavaScript will assume it is midnight and that the time zone is GMT. You can include the whole date including seconds if you want to.
Comparing dates
You can use dates as they are in IFs or WHILEs:
while (myDate<currentDate){
document.getElementById('messagediv').innerHTML='processing...';
currentDate=Date();
}
document.getElementById('messagediv').innerHTML='It's time!';
The loop will continue until the current time is more than the target time.
Date arithmetic
You do date arithmetic by extracting the bit (date, month, year) you want, doing the addition or subtraction and JavaScript will then put the changed bit back in:
var myDate=new Date('January 16, 1988');
myDate.setDate(myDate.getDate()+1);
Add an alert box and it should give January 17. The method getDate gets just the date part and then 1 is added. That value is then used to setDate. Change setDate to setYear and getDate to getYear and try again.
If the date had been January 31 and you added one JavaScript would handle that properly by making it February 1st. You might not expect that at first but it works well.
You can also subtract one date from another to find elapsed time the result (the gap) is in milliseconds so divide by 1000 for seconds, 60000 for minutes etc..




