However, a little more work needs to be done to create the tim e stamp of the event. We
cannot rely on the Date() co nstructor to d o the work this time but must do it manually.
For that purpose, we use the static Date.UTC() meth od to convert the opening time
of the ceremony to the millisecond representation, and pass the obtained milliseconds
as an argument to a Date() co nstructor. Brasília time is UTC minus three hours
in August. Tha t means the time of the opening ceremony is actually 8 p.m. plus
three hours when specified in universal time, which is 23. Finally, the next expression
returns the number of milliseconds since the epoch for the start time of the opening
ceremony:
Date.UTC(2016, 7, 5, 23)
The algorithm itself is not very complicated. Th e only way to compute a dierence
between two Date objects is to subtract their millisecond time representation s. After
that, necessary divisions are perf ormed to get the day s, hours, minutes, and seconds.
Here’s the cod e:
var msg = "Countdown to Rio 2016: ";
var now = new Date();
var opening = new Date(Date.UTC(2016, 7, 5, 23));
var seconds;
if (opening.getTime() > now.getTime()) {
seconds = opening.getTime() - now.getTime();
seconds = Math.floor(seconds / 1000);
msg += Math.floor(seconds / 86400) + " days, ";
seconds = seconds % 86400;
msg += Math.floor(seconds / 3600) + " hours, ";
seconds = seconds % 3600;
msg += Math.floor(seconds / 60) + " minutes, ";
msg += Math.floor(seconds % 60) + " seconds.";
}
document.write(msg);
You can see the result on the next screenshot.
Mike: The countdown is not running, is it?
Professor: No, it isn’t. The message is produced when the page is loaded and isn’t
updated until the next page reloa d. When you learn about the DOM and events, we are
going to change that and get a running counter withou t the need to reload th e page.3
3This example continues on page 237.
8.5. D ate Object 163
..................Content has been hidden....................

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