Java Reference
In-Depth Information
The World Time Method of the Date Object
trY it out
In the following code you use the toLocaleString() , toUTCString() , getTimezoneOffset() ,
toLocaleTimeString() , toTimeString() , toLocaleDateString() , and toDateString() methods and
write their values out to the page:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 7, Example 1</title>
</head>
<body>
<script>
var localTime = new Date();
var html = "<p>UTC Time is " + localTime.toUTCString() + "</p>";
html += "Local Time is " + localTime.toLocaleString() + "</p>";
html += "<p>Time Zone Offset is " +
localTime.getTimezoneOffset() + "</p>";
html += "<p>Using toLocalTimeString() gives: " +
localTime.toLocaleTimeString() + "</p>";
html += "<p>Using toTimeString() gives: " +
localTime.toTimeString() + "</p>";
html += "<p>Using toLocaleDateString() gives: " +
localTime.toLocaleDateString() + "</p>";
html += "<p>Using toDateString() gives: : " +
localTime.toDateString() + "</p>";
document.write(html);
</script>
</body>
</html>
Save this as ch7 _ example1.html and load it into your browser. What you see, of course, depends on
which time zone your computer is set to, but your browser should show something similar to Figure 7-1.
Here the computer's time is set to 09:28:318 PM on March 30, 2014, in America's Eastern Daylight
Time (for example, New York).
So how does this work? At the top of the page's script block, you have just:
var localTime = new Date();
This creates a new Date object and initializes it to the current date and time based on the client
computer's clock. (Note that the Date object simply stores the number of milliseconds between the date
and time on your computer's clock and midnight UTC on January 1, 1970.)
Search WWH ::




Custom Search