Java Reference
In-Depth Information
Calculations and Dates
Take a look at the following code:
var myDate = new Date("1 Jan 2010");
myDate.setDate(32);
document.write(myDate);
Surely there is some error—since when has January had 32 days? The answer is that of course it
doesn't, and JavaScript knows that. Instead JavaScript sets the date to 32 days from the first of
January—that is, it sets it to the 1st of February.
The same also applies to the setMonth() method. If you set it to a value greater than 11 , the date
automatically rolls over to the next year. So if you use setMonth(12) , that will set the date to
January of the next year, and similarly setMonth(13) is February of the next year.
How can you use this feature of setDate() and setMonth() to your advantage? Well, let's say you want
to find out what date it will be 28 days from now. Given that different months have different numbers
of days and that you could roll over to a different year, it's not as simple a task as it might first seem. Or
at least that would be the case if it were not for setDate() . The code to achieve this task is as follows:
var nowDate = new Date();
var currentDay = nowDate.getDate();
nowDate.setDate(currentDay + 28);
First you get the current system date by setting the nowDate variable to a new Date object with no
initialization value. In the next line, you put the current day of the month into a variable called
currentDay . Why? Well, when you use setDate() and pass it a value outside of the maximum
number of days for that month, it starts from the first of the month and counts that many days
forward. So, if today's date is January 15 and you use setDate(28) , it's not 28 days from the
15th of January, but 28 days from the 1st of January. What you want is 28 days from the current
date, so you need to add the current date to the number of days ahead you want. So you want
setDate(15 + 28) . In the third line, you set the date to the current date, plus 28 days. You stored
the current day of the month in currentDay , so now you just add 28 to that to move 28 days ahead.
If you want the date 28 days prior to the current date, you just pass the current date minus 28. Note
that this will most often be a negative number. You need to change only one line, and that's the
third one, which you change to the following:
nowDate.setDate(currentDay - 28);
You can use exactly the same principles for setMonth() as you have used for setDate() .
Getting time Values
The methods you use to retrieve the individual pieces of time data work much like the get methods
for date values. The methods you use here are:
getHours()
getMinutes()
 
Search WWH ::




Custom Search