- Learning Web Scripting Basics
- Testing the Script
- Q & A
To begin creating the script, open your favorite text editor and type the beginning and ending <script> tags, as shown here:
Storing Data in Variables
now = new Date();
Calculating the Results
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.
document.write("<p><strong>Local time:</strong> " + localtime + "</p>"); document.write("<p><strong>UTC time:</strong> " + utctime + "</p>");
These statements tell the browser to add some text to the web page containing your script. The output will include some brief strings introducing the results and the contents of the localtime and utctime variables.
Adding the Script to a Web Page
You should now have a complete script that calculates a result and displays it. Your script should match Listing 4.3.
Listing 4.3 The Complete Date and Time Script
<script> now = new Date(); localtime = now.toString(); utctime = now.toGMTString(); document.write("<p><strong>Local time:</strong> " + localtime + "</p>"); document.write("<p><strong>UTC time:</strong> " + utctime + "</p>"); </script>
To use your script, you need to add it to an HTML document. If you use the general template you’ve seen in the lessons so far, you should end up with something like Listing 4.4.
Listing 4.4 The Date and Time Script in an HTML Document
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Displaying Times and Dates</title> </head> <body> <h1>Current Date and Time</h1> <script> now = new Date(); localtime = now.toString(); utctime = now.toGMTString(); document.write("<p><strong>Local time:</strong> " + localtime + "</p>"); document.write("<p><strong>UTC time:</strong> " + utctime + "</p>"); </script> </body> </html>
Now that you have a complete HTML document, save it with an .html extension.