|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Adding JavaScript StatementsYour script now needs to determine the local and UTC times, and then display them to the browser. Fortunately, all of the hard parts, such as converting between date formats, are built in to the JavaScript interpreter. Storing Data in VariablesTo begin the script, you will use a variable to store the current date. You will learn more about variables in Hour 5, "Using Variables, Strings, and Arrays." A variable is a container that can hold a valuea number, some text, or in this case, a date. To start writing the script, add the following line after the first <script> tag. Be sure to use the same combination of capital and lowercase letters in your version because JavaScript commands and variable names are case sensitive. now = new Date(); This statement creates a variable called now and stores the current date and time in it. This statement and the others you will use in this script use JavaScript's built-in Date object, which enables you to conveniently handle dates and times. You'll learn more about working with dates in Hour 8, "Using Built-in Functions and Libraries." By the Way Notice the semicolon at the end of the previous statement. This tells the browser that it has reached the end of a statement. Semicolons are optional, but using them helps you avoid some common errors. We'll use them throughout this book for clarity. Calculating the ResultsInternally, JavaScript stores dates as the number of milliseconds since January 1, 1970. Fortunately, JavaScript includes a number of functions to convert dates and times in various ways, so you don't have to figure out how to convert milliseconds to day, date, and time. To continue your script, add the following two statements before the final </script> tag: localtime = now.toString(); utctime = now.toGMTString(); These statements create two new variables: localtime, containing the current time and date in a nice readable format, and utctime, containing the UTC equivalent. By the Way The localtime and utctime variables store a piece of text, such as January 1, 2001 12:00 PM. In programming parlance, a piece of text is called a string. You will learn more about strings in Hour 5. |
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |