Chapter 12
Math, Number, and Date Objects
Key Skills & Concepts
    Using the Math Object
    Understanding the Number Object
    Using the Date Object
image
In this chapter, you will learn about the JavaScript Math, Number, and Date objects, in that order. For each object, a short introduction is provided along with a description of why the object can be useful to you. Following that is a look at the various properties and methods that you can use for that object.
Using the Math Object
The Math object can be useful when you need to perform various calculations in your scripts. To begin, take a look at what the Math object is.
What Is the Math Object?
The Math object is a predefined JavaScript object. Like the other predefined objects you have studied in this book, the Math object gives you properties and methods to use. The Math object is used for mathematical purposes to give you the values of certain mathematical constants or to perform certain calculations or operations.
How the Math Object Is Useful
As mentioned, the Math object is useful when you need to make mathematical calculations in your scripts. For instance, if you need the value of pi for a calculation, the Math object gives you a property to use so you can get that value.
Also, if you need to find the square root of a number, a method of the Math object enables you to do this. Another thing this object provides is a way to generate random numbers in JavaScript, which you will find useful in certain scripts.
Properties
The Math object gives you a number of properties that can help you if you need to perform certain mathematical calculations. Table 12-1 lists the properties of the Math object, with the values of each.
image
image
Table 12-1    Properties of the Math Object
As you can see in Table 12-1, all of the properties simply hold numeric values that can be useful in mathematical calculations. Because these are irrational numbers, the values listed are nonterminating and are thus approximations. Note that these properties are in “all-caps.” This is because they are constant values, and the naming convention for such values is that they must be in all capital letters.
Using the Properties
The properties contain read-only values, which tend to be useful in particular types of calculations. For instance, if you want to find the area of a circle, you use the formula Area = pi*r2. Knowing that, you could write an application to determine the area of a circle based on the radius input by a viewer. You could use the following code, starting with the HTML code:
image
Next, the JavaScript code:
image
image
This code first grabs the form element by its id (getarea) and assigns it to a variable named get_area. When the form is submitted, it grabs the value input in the text field for the radius and assigns it to a variable named rad.
Next, the code performs two checks. It checks that the length property of rad is not less than 1, to ensure that the viewer entered data into the field. If it is less than 1, the code gives an alert asking the viewer to enter the information. Next, it checks to see if the value of rad is not numeric. This is done by testing whether or not the value can be coerced into a numeric value using the unary plus operator (except for zero, which is specified so that it remains the numeric zero rather than being coerced to the Boolean value of false). If the number cannot be coerced, it is assigned a Boolean value of false. The if statement will then check the value of rad, and will send the viewer an alert saying that the radius must be numeric if it could not be coerced to a number.
Finally, if the data entered passes those tests, the calculation of the area of the circle is performed and assigned to a variable named the_area. Notice that for now you multiply the radius by itself to get the radius squared. When you get to the math methods in the next section, you will see that the method pow() may be used instead.
Once the calculation is complete and assigned to the variable, an alert is displayed to the viewer with the area in generic “square units.” The script could of course be altered to suit your needs or to offer options (centimeters, inches, or other units of measure).
Figure 12-1 shows the result of running this script in a browser and entering 2 into the text field.
image
image
Figure 12-1    The area of the circle is displayed for the viewer.
Methods
The methods of the Math object enable you to perform certain calculations that can be helpful in your scripts. Table 12-2 lists various methods of the Math object and briefly describes the purpose of each. Each method is discussed in more detail in the following sections.
image
image
Table 12-2    Methods of the Math Object
The Basic Methods
For the purpose of this book, “basic methods” are defined as the methods that take in a single number, do a simple calculation with it, and return a value. Grouping the methods in this way avoids the need to list each method with the same sort of example—it is not any sort of official organization of the methods, just a way to expedite this discussion.
The following basic methods are the ones that work in generally the same way:
    abs()
    acos()
    asin()
    atan()
    cos()
    exp()
    log()
    sin()
    sqrt()
    tan()
Each of these basic methods takes a numeric value and sends back another value. Since the general usage is the same, this discussion uses sqrt() as an example of how the rest could be used to get their various values. If you need to know what type of value is returned from a different method, refer to Table 12-2 to see what each method does.
The easiest way to use the sqrt() method is to input a positive number as the argument to the method, as shown in the following example:
image
This alerts the value of the positive square root of 4, which is 2.
Instead of calculating a static number, you could get the user to input a number, and then send an alert to the user with the square root of the number input by the user. You could do this using the following code, starting with the HTML code:
image
Next, the JavaScript code:
image
image
When the user submits the form, the value input into the text box is assigned to the thenum variable. Next, the function checks to see if the field was left empty or the data entered was not numeric. After that, it checks to see if the viewer entered a negative number. Any of these situations will alert the viewer to the error. Otherwise, the Math.sqrt() method is called using the value of thenum as an argument. This returns the number’s square root, which is then assigned to the variable named theroot. Finally, an alert appears telling the user the square root information.
The result of this script when the viewer enters the number 4 is shown in Figure 12-2.
image
image
Figure 12-2    The square root is displayed for the viewer.
The other methods in this section work in much the same way; they just return different results such as absolute values, tangents, or logarithms.
The Two-Argument Methods
This section discusses the methods that take two arguments instead of just one. These methods include the following:
    atan2()
    max()
    min()
    pow()
The max() and min() methods are very similar, while the pow() method does something a bit different.
The max() and min() Methods   The max() method takes two or more numbers and returns the largest number. The min() method also takes two arguments, but returns the smaller number. You could use these methods in a script that enables the viewer to enter two numbers and then alerts the user which number is larger.
The following example code uses both of these methods and gives the viewer the results in an alert. First, the HTML code:
image
Next, the JavaScript code:
image
This form asks the viewer for two numbers and assigns them to variables. A check is performed to ensure that numeric values are entered. If so, it takes the maximum and minimum from both numbers and assigns the values to variables. Those variables are then used to check whether they are equal. If so, an alert comes up saying they are; otherwise, an alert pops up with the results.
The following illustration shows the results of this script in a browser if the viewer enters 2 as the first number and 54 as the second number.
image
The pow() Method The pow() method takes two arguments and calculates the value of the first argument to the power of the second argument. For instance, the following code would return the value of 2 to the third power:
image
Other than its difference in calculations, you can use it in the same general way that you used the other two-argument methods by assigning the result to a variable and then using the variable in a script. As an example, you could use the following script, starting with the HTML code:
image
Next, the JavaScript code:
image
image
Using this code, if the viewer enters 2 as the first number and 3 when asked for a power, the script will compute the result of 2 to the third power. The viewer then is given an alert showing the answer. Clicking the button in the HTML code is how the viewer starts the function. The result of this script when the numbers 2 and 3 are input is shown here:
image
Now that you know about the two-argument methods, take a look at some other methods that haven’t been covered yet.
The Other Methods
These methods take a single argument, but what each does with that argument warrants a closer look. The individual methods include the following:
    ceil()
    floor()
    round()
The ceil() Method   The ceil() method stands for ceiling and returns the smallest integer that is greater than or equal to the number sent as the argument. This method is used mainly when there are likely to be numbers after the decimal point in a number. It rounds the number up to the next highest integer, unless the number is an integer already. In that case, the same number is returned (because it can be equal). For instance, Math.ceil(12.23); would return 13, but Math.ceil(12); would return 12.
The following script shows an example of how the ceil() method can be used to return different values, starting with the HTML code:
image
Next, the JavaScript code:
image
This script displays an alert that states the ceiling of the number entered by the viewer. The following illustration shows the result of this in the browser when the viewer enters 4.55 at the prompt.
image
The floor() Method   The floor() method is like the ceil() method, but it goes the opposite way. The floor() method returns the largest integer less than or equal to the argument sent to the method. This rounds down to the next lowest integer, unless the argument is an integer already. In that case, it returns the same integer since it is already equal to an integer. Basically, this method just removes the decimal part of a number and leaves the integer as the result.
For instance, Math.floor(12.23); will return 12 and Math.floor(12); will also return 12. You can use the floor() method in the same way the ceil() method was used in the preceding section—by assigning the result to a variable.
The round() Method   The round() method works like the previous two methods, but instead rounds the number entered as the argument to the nearest integer whether it is greater or less than the number. Any number having the decimal portion’s value at .5 or greater will be rounded up, while any decimal portion with a value less than .5 is rounded down.
The .5 cutoff is strict, so Math.round(12.49999999); would return 12 even though your tendency may be to round it up.
The random() Method
The random() method is very useful for creating scripts that require random integers. It returns a random number between 0 and 1. This means that you get a number with a decimal that can be quite long and not useful on its own. For instance, it might return something like 0.36511165498095293.
To get a random integer that you can use, you need to do some things to get the type of value that you want to use.
Random Integers   To get a random integer, the first thing you will want to do is to make the result have a greater range of values so that you are not stuck between 0 and 1. To get a greater range of values, you can multiply the result of the random() method by an integer to create a larger range. Like an array, the range would begin counting from 0; so, to get a range of five possible integers, you would multiply the result by 5. The following code shows how you can do this:
image
This gets the result between 0 and 4, but does not give you an integer yet. The number could still come out as a long decimal number.
To get an integer between 0 and 4, you need to find a way to make all of these decimal numbers convert to integers. Recall that earlier you ran through three methods, floor(), ceil(), and round(), that converted numbers to integers in various ways. The floor() method is the one you will choose here because it simply removes the decimal places after the integer and gives you the integer portion of the number.
To use the floor() method, you could write the following code:
image
The floor() method takes in the value of the rand_num variable as an argument and then gives you an integer from it.
If you want to save a line of code, you could get a little fancy. You could just insert the random() method and calculation as the argument to the floor() method. You can do this because the result of the calculation, Math.random*5, is a number, and the floor() method can take a number as an argument. The following code shows how you can code this on a single line:
image
Now the variable rand_int will have the value of a random integer between 0 and 4. As you might have noticed, this sort of number range could be quite useful with arrays. This is how you can begin to code some fun scripts with random numbers.
Random Numbers for Scripts   Now you can have a little fun with the Math object by using the random() method. By setting up some arrays, you can create a script that provides random quotes or shows a random image each time the page is loaded.
Random Quotes for Fun If you have thought about adding a quote to your page but don’t want to deal with changing the quote all the time to have something different, a random-quotes script could be just the thing for you.
To make such a script, you first need some quotes to use. Suppose you want to set up ten different quotes that will be displayed in random order each time the page is loaded. Since you have a number of values that are similar (and so that you can use them with the random integer later), you should use an array so that you can store all of these values and retrieve them easily.
So, you need to set up an array with ten elements similar to the following example, in which each element is a random (and perhaps peculiar) quote that I have thrown into the mix for you:
image
Now that you have this odd list of quotes in an array, you can use them by generating a random integer.
You need a random integer between 0 and 9 (ten numbers), so you can use the following code to assign a random integer between 0 and 9 to a variable:
image
Now the value of the variable rand_int will be a random integer between 0 and 9. You can use it to access the element of the array whose index number matches the random integer in the rand_int variable. You just need to access the array element using the variable as the index number, as in the following example:
image
You can write this value in the body of the page using the innerHTML property of the div element, as in the following example code. The HTML document is saved as random_quotes.html and the JavaScript file is saved as random_quotes.js. The HTML code:
image
The JavaScript code:
image
image
The code writes one of the random quotes on the page based on the random integer value in the rand_int variable. A default quote (the first one in the array data) is provided for those without JavaScript, which is then overwritten with the random quote if JavaScript is available. Reloading the page enables the random number to be reset and will probably (though not necessarily, because it is random) show a different quote.
Figure 12-3 shows one of the possible results of this script when run in a browser.
image
image
Figure 12-3    A possible result of using the random-quote script
Figure 12-4 shows another one of the possible results of this script when run in a browser. You can keep getting different (or sometimes the same) results by refreshing the page.
image
image
Figure 12-4    Another possible result of using the random-quote script
Now that you can write random quotes into a page, how about displaying a random image? It is very similar to the last script; you just need to make some small adjustments.
Random Images for the Updated Look   A random-image script can give your page the feel of being updated without requiring you to change an image all the time. Of course, the images all need to fit the content where you decide to place the randomly chosen image. A random-image script could be useful, for example, for an art gallery to display its collection.
The first thing you need is an array of image URL addresses (which can be local or absolute—local addresses are used here). The array used for this script is shown in the following example code:
image
This array sets up the addresses of images that can be displayed at random each time the page is loaded.
Next, you need a way to get a random integer between 0 and 9. This is the same as in the previous random-quote script:
image
The next step is to access the array in the body section of the document to show a random image from the array when the page is loaded in the browser.
The following code enables you to display the random image using the src property of an img element. The HTML file is saved as random_images.html and the JavaScript file is saved as random_images.js. First, the HTML code:
image
Next, the JavaScript code:
image
As you can see, this is quite similar to the random-quote script. Since you are changing an image, you can assign the result to the src property available on image elements to dynamically change the image. If you need to change text as well, you could change this to use innerHTML as you did with the random quotes.
NOTE
image
For this example, the images are saved as image0.gif, image1.gif, and so on; however, you could save your image files under any name you like.
This discussion of the random() method could go on for some time because there are numerous things that you could randomize. However, you now know the basics of how this feature works, so it’s time to move on.
Ask the Expert
Q:  Will I ever have any use for any of the properties of the Math object? They are all numbers that I don’t even use!
A:  This depends on how often you perform different types of calculations. It would be unlikely for you to use any of them as a beginner, but there are some scripts out there that use them for various advanced purposes, such as JavaScript calculators, graphical objects (such as the canvas element), and more.
Q:  I have no interest in writing a calculator. Do I really have to bother memorizing all the properties of the Math object?
A:  Well, probably not, since a situation where you need to use them probably won’t come up all that often. It is good to have a reference on hand just in case, though, and to know generally what they are, since they appear in scripts on the Web from time to time.
Q:  Some of these properties and methods could be handy if I don’t have a calculator around. I could write a little script to calculate some things for myself, couldn’t I?
A:  Of course! Just be sure to double-check the numbers with something you know the answer to first to be sure that there are no mistakes in your code.
Q:  The random() method is fun so far, but I can’t think of anything else I could use it for. Could you give me some ideas for using it to do other things?
A:  There are a number of other things you could use it for. You can randomize pretty much anything that can be displayed with an HTML tag or plain text, so try out some ideas and see if they work for you. Here are some thoughts off the top of my head for you, though: random links, random linked images, random tasks for a JavaScript game of some sort (like rolling dice or drawing a card), random page greetings, random alerts… and I’m sure there are plenty more.
Try This 12-1 Display a Random Link on a Page
image
This script enables you to work with the random() method a little more by enabling you to create a script to display a random link on a page.
Step by Step
1.  Create an HTML page with script tags that point to an external JavaScript file named prjs12_1.js. Add a heading that says “Random Link” and add a div element with an id of random_link. Inside the div element, insert a default link for those without JavaScript. Save the HTML file as pr12_1.html.
2.  When complete, the body of the HTML file should look like this:
image
3.  Create an external JavaScript file and save it as prjs12_1.js. Use it for steps 4–7.
4.  Create a set of five Web addresses in an array. Use the following addresses or some of your own choosing:
http://www.scripttheweb.com
http://www.webxpertz.net
http://www.duckduckgo.com
http://www.yahoo.com
http://www.google.com
5.  Use the random() method to create a random integer you can use to access the array with the integer as an index number.
6.  Display a random link on the page in the format shown next by changing the innerHTML property of the div element with the id of random_link:
image
7.  When complete, the JavaScript file should look like this:
image
image
8.  Save the JavaScript file and open the HTML file in your Web browser. Try reloading a few times to see how the random addresses show up for the link.
Try This Summary
In this project, you were able to use your knowledge of the Math object. Using the random() method, you created a Web page that displays a link that goes to a random Web address.
image
Understanding the Number Object
The Number object is another predefined JavaScript object that offers several useful properties and methods for use with numbers. Its most common use is to access some of its helpful properties that represent certain values that can aid you when creating scripts.
Properties
Table 12-3 lists the properties of the Number object and briefly describes the purpose of each. Each property is described in more detail in this section.
image
image
Table 12-3    Properties of the Number Object
The MAX_VALUE Property
The MAX_VALUE property is a constant number value, approximately 1.79E+308. The reason this property is helpful is that any number greater than its value is represented as infinity in JavaScript. Thus, using it in a comparison could provide a way to avoid calculations that are too large to display a numerical value. The following code is an example of how this works:
image
Assuming num1, num2, and num3 were entered by the viewer, the alert, instead of displaying the word “infinity” as the answer, informs the viewer to try entering smaller numbers for the calculation if the value of big_num is greater than the value of the MAX_VALUE property.
The MIN_VALUE Property
The MIN_VALUE property is a constant number value, approximately 5e –324. The reason this property is helpful is that any number less than its value is represented as negative infinity in JavaScript. Thus, using it in a comparison could provide a way to avoid calculations that are too small to display a numerical value. The following code is an example of how this works:
image
Assuming num1, num2, and num3 were entered by the viewer, the alert tells the viewer to try entering larger numbers for the calculation if the result of the calculation is less than the value of the MIN_VALUE property.
The NaN Property
The NaN property is a value that represents “Not a Number.” It is displayed by the browser as a string value of NaN and is not equal to any number or another instance of NaN.
The NEGATIVE_INFINITY Property
The NEGATIVE_INFINITY property is a constant value that represents negative infinity. It can be used in a similar fashion to the way MIN_NUMBER and MAX_NUMBER are used.
The POSITIVE_INFINITY Property
The POSITIVE_INFINITY property is a constant value that represents positive infinity. It can be used in a similar fashion to the way MIN_NUMBER and MAX_NUMBER are used.
NOTE
image
Infinity behaves differently in mathematical equations than other numbers. For more information on this, see tutorial.math.lamar.edu/Classes/CalcI/TypesOfInfinity.aspx
Methods
Table 12-4 lists the methods of the Number object and briefly describes the purpose of each. The following sections discuss each method in more detail.
image
image
Table 12-4    Methods of the Number Object
The toExponential(), toFixed(), toPrecision(), and toString() Methods
These methods return a string value representing what the Number object would look like formatted in a particular way. Note that these methods cannot be used with a number itself (a numeric value), as in the following code:
image
This will cause a JavaScript error because it expects a Number object. To avoid this, use the methods by assigning numeric values to variables (which will make them Number objects), as in the following code:
image
NOTE
image
You could also use the constructor syntax of var the_num = new Number(10); and it will also be valid.
The toExponential() Method
The toExponential() method returns a string representing a Number object in the form of exponential notation. Thus, the following code would write the result of 1.0e+1 (or a similar notation, depending on your browser) on the screen:
image
The toFixed() Method
The toFixed() method returns a string representing a Number object rounded to the specified number of places after the decimal. For instance, if you need to format the results of calculations to appear as monetary values, you could use this method to get the result of your calculation rounded at the second digit after the decimal and displayed in your currency format. For example, this code uses dollars and cents:
image
The result of the calculation for one share is 285.7142857142857, but since it is displayed using the toFixed() method on it with 2 as the argument, the sentence displays as follows:
image
The toPrecision() Method
The toPrecision() method returns a string representing a Number object rounded to the specified number of significant digits. This is for all digits before and after the decimal. Thus, if you wanted a number like 45.57689349 rounded to five significant digits, you could use the following code:
image
The browser will alert the string 45.577, which is the number rounded to five significant digits (two before and three after the decimal place in this case).
The toString() Method
The toString() method returns the string value of a Number object (or a numerical variable value). This can be useful if you want to convert a numerical value to its corresponding string value (for example, change 10 to “10”).
The toSource() Method
The toSource() method returns a string value that represents the source code of the object. With the predefined Number object, this method returns the value of the constructor property. This method is most often called by JavaScript internally and is less likely to be used in code.
The valueOf() Method
This is another method that is mainly used by JavaScript internally. For now, you just need to know that it is a valid method of the Number object.
The parseInt() and parseFloat() Methods
While not methods of the Number object, these two methods are useful when you need to get a numeric value from a mixed string. They work in a similar fashion, with parseInt() only grabbing the integer portion of a number and parseFloat() grabbing the integer and any numbers after a decimal. Here is how they work:
    If the first character in the string is anything other than a number, a plus (+), or a minus (–), then both methods return NaN.
    For parseInt(), if the first character is a number (other than zero), plus, or minus, then each character is evaluated until a non-numeric character is reached (with the exception of hexadecimal values, where certain other characters such as x and A are allowed). The number obtained from this process will be returned. If the first character is zero and the number is not hexadecimal, then zero is returned.
    For parseFloat(), if the first character is a number, plus, or minus, it will evaluate each character and continue if it finds a dot (.) followed by additional numbers, until a second non-numeric character is reached. If the number begins with zero and the number is not hexadecimal, then any leading zeros are ignored until another number is reached. The number obtained from this process will be returned. Hexadecimal numbers return zero.
Some examples of the values returned for each method will show how the rules work:
image
When using parseInt(), you are allowed to define a second argument, called the radix. This gives you the opportunity to specify the type of number to be returned. Here are some examples:
image
As you can see, the same value can have different results depending on the specified radix. The parseFloat() method does not have this option, since by design it will only parse decimal values.
TIP
image
When the radix argument is left off, JavaScript decides what type of value to return. In some cases, this can lead to unexpected results. To avoid this, it is best to specify the radix value, even when working with and expecting decimal values (specify the radix as 10).
Using the Date Object
The Date object is another predefined JavaScript object. It enables you to set certain time values and to get certain time values that you can use in your scripts. To use this object, you need to create an instance of the object to which you can refer.
To create an instance of the Date object, you use the new keyword (as you have with a number of other objects), as shown in the following example:
image
You would replace instance_name with a name that you want to use for the instance of the Date object. So, if you wanted an instance named rightnow, you could use the following code:
image
Now you have an instance of the object named rightnow.
When using the constructor, the default date is the current date; however, you can specify a different date if needed, as in the following code:
image
Once you have an instance of the object, you can use the properties and methods of the Date object to perform various tasks (such as create JavaScript clocks). These properties and methods are described in the following sections.
Properties and Methods
The Date object doesn’t give you properties (outside of constructor and prototype), but it does have quite a large number of methods you can use. Table 12-5 lists various methods of the Date object and the purpose of each method. Each method is discussed in more detail in the sections that follow.
image
image
image
Table 12-5    Methods of the Date Object
Now that you have the long list of methods, take a look at them in a little more detail, beginning with the methods used to get date values in an instance of the Date object.
Methods That Get Values
Methods that get values enable you to get various time and date values that you can use in your scripts. The methods that enable you to get values for an instance of the Date object include the following:
    getDate()
    getDay()
    getHours()
    getMilliseconds()
    getMinutes()
    getMonth()
    getSeconds()
    getTime()
    getTimezoneOffset()
    getYear()
    getFullYear()
    getUTCDate()
    getUTCDay()
    getUTCFullYear()
    getUTCHours()
    getUTCMilliseconds()
    getUTCMinutes()
    getUTCMonth()
    getUTCSeconds()
To use these methods, you need an instance of the Date object. Once you have that, you can call any of the methods by using the instance name. The following is the syntax for doing this:
image
You would replace instance_name with the name of your instance of the Date object, and you would replace method with the method function you wish to use.
So, if you wanted to use the getDate() method with an instance of the Date object named rightnow, you would use the following code:
image
This assigns the value returned from the getDate() method to a variable named theday.
Because the values returned from the Date methods are often numeric, the methods need to be explained a bit further; thus, the following sections take a look at these methods more closely.
The getDate() Method
The getDate() method enables you to get the day of the month for use in a script. The value returned is a number that represents the day of the month. So, if it is the 5th of the month, the getDate() method would return 5. If it is the 22nd, the getDate() method would return 22. This method is nice because it is fairly straightforward.
The getDay() Method
The getDay() method enables you to get the day of the week; however, rather than returning a name such as Monday or Friday, it returns a number. The number represents the number of days into the week (0–6) rather than the day of the week you would commonly have in mind (1–7). So, if it is Sunday, the method returns 0; and if it is Wednesday, the method returns 3. You have to remember that it counts from 0 when you begin using it in your scripts. Many of the methods that follow will count beginning at 0.
The getHours() Method
The getHours() method enables you to get the number of hours into the day (0–23). The count begins at 0. So, when it is midnight, the method returns 0; and when it is 2:00 P.M., it returns 14.
The getMilliseconds() Method
The getMilliseconds() method enables you to get the number of milliseconds stored in the instance of the Date object (0–999).
The getMinutes() Method
The getMinutes() method enables you to get the number of minutes stored in the instance of the Date object (0–59). Again, the counting begins at 0. So, if it is 2:00 (either A.M. or P.M.), or any hour on the dot, the method returns 0; and if it is 2:23, the method returns 23.
The getMonth() Method
The getMonth() method enables you to get the number of months stored in the instance of the Date object (0–11). This method also begins counting at 0, which makes the result a little tricky. For instance, if it is January (the month people tend to think of as 1), the method returns 0; and if it is October (the month people tend to think of as 10), the method returns 9. This is one you have to watch a little more closely when you use it in scripts, because you will need to remember to make an adjustment if you want to use numeric dates (like 10/24/2000).
The getSeconds() Method
The getSeconds() method enables you to get the number of seconds stored in the instance of the Date object (0–59). So, if the time is 2:42:23, the method returns 23; and if the time is 2:23:00, the method returns 0.
The getTime() Method
The getTime() method gets the time (in milliseconds since January 1, 1970, at midnight) for an instance of the Date object. So, if you wanted to know the number of milliseconds since that date at your current time, you could use the following code:
image
This assigns the result of the method to a variable so that you can use it later if you need it in your script.
The getTimezoneOffset() Method
The getTimezoneOffset() method gives you the number of minutes that separate the local time from GMT. So, if you are six hours apart from GMT, the method would return 360 (6 × 60); and if you are only one hour apart, the method returns 60.
The getYear() Method
This method returns the last two digits of the year (at least if the year is between 1900 and 1999). For instance, if the year is 1988, the method returns 88. After the year 2000, some browsers will return a three-digit year and others will return a four-digit year. To avoid this, you can use the getFullYear() method, which is supported by the newer browsers and returns a four-digit year.
The getFullYear() Method
The getFullYear() method is very similar to the getYear() method, except it returns a four-digit year consistently to avoid the year 2000 problem.
The getFullYear() method works like the getYear() method, but you do not need to run any extra checks to be sure the year is correct:
image
This assigns the value returned by the method to the theyear variable. This time, the value is already four digits and won’t need any adjusting.
The UTC Methods
These methods work the same as their counterparts (for example, getDate() and getUTCDate() work the same), but return the information in terms of Universal Time rather than the viewer’s local time.
Now that you have seen the methods that get values, take a look at the methods that enable you to set values for an instance of the Date object.
Methods That Set Values
The methods that set values work with the same types of values as the methods that get values. The methods that enable you to set values for an instance of the Date object include the following:
    setDate()
    setHours()
    setMilliseconds
    setMinutes()
    setMonth()
    setSeconds()
    setTime()
    setYear()
    setFullYear()
    setUTCDate()
    setUTCFullYear()
    setUTCHours()
    setUTCMilliseconds()
    setUTCMinutes()
    setUTCMonth()
    setUTCSeconds()
To set these, you send them a numeric argument based on the time or date you want to use. For instance, if you wanted to set the day of the month for an instance of the Date object, you could use the following code:
image
This would set the day of the month to the 22nd for the rightnow instance of the Date object.
The other methods work in the same way. In order to know what value needs to be sent to one of these methods, take a look at what type of value is returned by its counterpart in the methods that get values. The argument the method will expect will be a value like the one returned by the method.
Other Methods
The remaining methods perform various tasks that the other methods don’t cover in some way.
The parse() Method
The parse() method is used to find out the number of milliseconds since January 1, 1970, at midnight for a date string (such as Dec 12, 1999) input as an argument. This is often used with the setTime() method since it needs an argument in milliseconds to set the time. You could use the parse() method to find the number of milliseconds since January 1, 1970, for the date Dec 12, 1999 at midnight (the rightnow instance of the Date object will use this as the date that all of the methods will use to return values), as shown in the following code:
image
This code parses the date into a number of milliseconds, and then sends it to the setTime() method used with the rightnow instance of the Date object.
The toString(), toDateString(), toTimeString(), toLocaleDateString, and toLocaleTimeString() Methods
These methods return a string representing the date and time, or a portion thereof. For instance, the toString() method returns a date in string format. You can use it to get a formatted date for an instance of the Date object, as shown in the following code:
image
This will assign a date string value to the variable thedate. The value of the string depends on what browser the viewer is using to view the page. It can then be written to the page or used with other methods of the Date object in a script.
The toGMTString() Method
The toGMTString() method returns a date string in GMT format. You can use it to get the GMT format for an instance of the Date object, as shown in the following code:
image
This will assign a value, such as Wed, 21 Dec 2003 11:12:44 GMT, to the variable thedate. It can then be written to the page or used with other methods of the Date object in a script.
The toLocaleString() Method
The toLocaleString() method returns a date string in the format of the viewer’s locale. You can use it to get the locale format for an instance of the Date object, as shown in the following code:
image
This will assign a date string value to the variable thedate. The value of the string depends on what browser the viewer is using to view the page. It can then be written to the page or used with other methods of the Date object in a script.
Now that you have the methods down, see if you can have a little fun with the Date object.
How About Some Date Scripts?
With the technical overview out of the way, you are ready to create some scripts that use the methods of the Date object. First you will write a script to display the date on the page, and then you will create a script for a simple status bar clock.
Write the Date on the Page
To write the date on the page, you need to use some of the Date object methods to get the values you need. Suppose you want to write a date with the format of Tuesday, M/D/Y (month, day, year). To do this, you need to find out the day of the week, the month, the day of the month, and the year. You can do this using the getDay(), getMonth(), getDate(), and getFullYear() methods.
The following script will write the date to the page. First, the HTML code (save as write_date.html):
image
Note the comment within the div element. If you want to make this accessible to browsers that do not support JavaScript, you can place a call to a PHP (or other server-side technology) script here for those lacking JavaScript. For example, if you had the page set up to parse PHP, you could use the following to display the date much like the JavaScript code will:
image
You will see that the PHP script is much shorter than the JavaScript script due to its built-in date-formatting capability. The date displayed may differ from the viewer’s date as it displays the date on the Web server. An in-depth discussion of server-side technology is beyond the scope of this book, but this serves as an example of a way to provide the same basic feature for those without JavaScript.
Next, the JavaScript code (save as write_date.js):
image
This script sets the results of the methods to variables. It then creates an array to hold the days of the week, which are later accessed using the number returned from the getDay() method as the index. The script then makes an adjustment, adding 1 to the number returned by the getMonth() method, so that the month will show up the way you would expect it (recall that it counts months starting at 0 instead of 1, so this ensures that January is represented by the number 1 rather than 0, for example).
The formatted output is written onto the page for the viewer to see. The result of this script when run in a browser is shown in Figure 12-5.
image
image
Figure 12-5    The date is shown on the page.
Create a Simple Clock
To create a simple clock, you need the hours, minutes, and seconds of the current time. To get these, you can use the getHours(), getMinutes(), and getSeconds() methods.
The following code will create a clock that is displayed on the page. First, the HTML code (save as clock.html):
image
CAUTION
image
If you use a server-side script as a backup to the JavaScript clock, you almost surely do not want it to update every second because this could put undue strain on the Web server. In such a case, it is often best to simply display the time without updating it.
Next, the JavaScript code (save as clock.js):
image
The script creates a function that sets the results of the methods to variables. It takes the hours variable and sets the ap variable to p.m. if hours is greater than or equal to 12 and sets it to a.m. if hours is less than 12 (at this point the hours variable still holds 13 for 1 p.m., 14 for 2 p.m., and so on). Once this is done, the hours variable is adjusted so that it will display the expected value for a 12-hour clock.
The script then adjusts the values of the variables that show the minutes and seconds by adding a leading 0 when the number is less than 10. This way the clock will show 12:02:34 for 12:02:34, instead of leaving out the 0 and displaying 12:2:34 (this can also be done for the hours variable if you would like it to have a leading zero).
At the end, the function displays the output on the page. The function is initially called right after it is defined. The function is repeated at intervals of 1000 milliseconds, or 1 second. This enables the clock to stay current. The results of this script when run in a browser are shown in Figure 12-6.
image
image
Figure 12-6    The current time is displayed on the page.
Try This 12-2 Create a JavaScript Clock
image
This project enables you to work more with the methods of the Date object, as well as learn how to adjust the values that are returned so they can be used in various ways. This creates a JavaScript clock with a few more options than your simple clock in the previous section.
Step by Step
  1.  Create an HTML page with script tags that point to an external JavaScript file named prjs12_2.js. Add a heading that says “Current Time” and add a div element with an id of my_clock. Save the HTML file as pr12_2.html.
  2.  When complete, the body of the HTML file should look like this:
image
  3.  Create an external JavaScript file and save it as prjs12_2.js. Use it for steps 4–7.
  4.  Write some code that will display a clock. In this clock, include the following information:
  5.  The time with hours, minutes, and seconds
  6.  Whether it is A.M. or P.M.
  7.  The date in the form mm/dd/yyyy
  8.  This will be a 12-hour clock, so be sure to adjust the value of the hours so that they stay between 1 and 12. Also, note the format of the date and adjust the month and day values accordingly.
  9.  Begin the clock, and have it update every second.
10.  When complete, the JavaScript file should look like this:
image
11.  Save the JavaScript file and open the HTML file in your browser. The time and date should appear on the page.
Try This Summary
In this project, you used your knowledge of the Date object. Using the methods of the Date object, you created a clock with a date that appears on the Web page.
image
image
Chapter 12 Self Test
image
  1.  What do the properties and methods of the Math object enable you to do?
A.  Take the square roots and other such values of strings and return a number
B.  Perform mathematical calculations
C.  Go to math class to learn new theorems
D.  Nothing, they are useless
  2.  The __________ property holds the value of Euler’s constant.
  3.  The LN10 property holds the value of the natural __________ of 10.
  4.  The LOG10E property holds the value of the logarithm of 10*E.
A.  True
B.  False
  5.  Which of the following would correctly write the value of pi on a Web page?
A.  document.write(Math.Pi);
B.  document.write(Math.pi);
C.  document.write(Math.PI);
D.  document.write(Date.PI);
  6.  The __________ property holds the value of the square root of 2.
  7.  The abs() method returns the __________ value of a number sent to it as an argument.
A.  absent
B.  absurd
C.  absolute
D.  absolute square root
  8.  The __________ method returns the arcsine of a number sent to it as an argument.
  9.  The pow() method returns the numeric value of the __________ argument raised to the power of the __________ argument.
10.  Which of the following would correctly generate a random number between 0 and 7?
A.  var rand_int= Math.floor(Math.random()*7);
B.  var rand_int= Math.floor(Math.random()*6);
C.  var rand_int= Math.floor(Math.random()*8);
D.  var rand_int= Math.sqrt(Math.random());
11.  The __________ method returns the square root of a number sent to it as an argument.
12.  What must be created in most cases before the Date object’s properties and methods can be used?
A.  Nights string
B.  A number for reference to the date
C.  A time for the date to be set
D.  An instance of the Date object
13.  The __________ method returns the number of days into the week.
14.  The getMonth() method returns the same number as the number that represents the current month (for example, returns 1 if the current month is January).
A.  True
B.  False
15.  Which of the following correctly assigns the day of the week for an instance of the Date object named rightnow to a variable named weekday?
A.  var weekday= rightnow.getDate();
B.  var weekday= rightnow.getDay();
C.  var weekday= right now.getDay();
D.  var weekly= rightlater.getMinutes();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.17.64