The JavaScript Date Object - The JavaScript Diaries: Part 15 - Page 4
[previous]
The JavaScript Diaries: Part 15 - The Date Object
Let's take a script borrowed from Doc JavaScript and adapt it a bit for our purposes. We're going to write a script which will tell you what day of the week you were born.
Most of this should look pretty familiar. You've got your basic array, conditional statements, prompt and alert boxes. Now let's break it down and see what we did.
|
With a bit of forethought, you should be able to handle most of these scripts. If it gets a bit out of hand, we have forums where you can ask for help.
Now, let's find out how many days are left in the current month. A variation of this script might come in handy when prorating rental fees or calculating the number of days left in a sale. Here's the script (adapted from JavaScript Source).
And this is what it looks like:
This one should be pretty easy to understand. The first four variables are like the previous examples. The next one, monarr
, is given the value of an array whose elements are the length of each month, from January to December. There's also a formula for determining a leap year. You might want to add this to your collection of snippets. (You do have a collection of snippets, don't you?)
In the script above, if the year is a leap year, then the second element in the array of the variable monarr
is equal to 29. If you think about it, the array represents the number of days in the months, beginning with January, which has an index number of "0". That means that the second element in the array (monarr[1]
) is February, with an index number of "1." The leap year calculation then changes its array element to "29" for this calculation.
The "Y2K" Problem
You will find many scripts have what is called the "Y2K fix." That means they will have something like the following code:
getFullYear
method.
(This is why the getYear
method is deprecated. This also applies to the setYear
method, which was deprecated in favor of the setFullYear
method.)
If you come across a script like the one above, just change the getYear
method to the getFullYear
method and remove the following line:
Going Further
That wraps up this section on the Date()
object. As you can see it has many different applications. I didn't go into too much depth as I wanted you to be able to digest this in small bits. (Perhaps I'll do an advanced tutorial at a later date, as I mentioned earlier.) Don't be afraid to get involved in calculations using this object. Just take your time. Also, be sure to dissect other scripts to see how they work. Once you break them down, it's not too difficult to see what makes them tick. You can find a large number of them over at JavaScript Source and JavaScripts.com.
Until next time ... keep on scriptin'!
[previous]
URL: