HTML and CSS Reference
In-Depth Information
To create the calcDays() function:
1. Return to the functions.js file in your text editor.
2. At the bottom of the file, insert the following function, as shown in Figure 11-16:
function calcDays(currentDate) {
// create a Date object for January 1 of the next year
// calculate the difference between currentDate and January 1
}
Figure 11-16
inserting the calcdays() function
3. Save your changes to the file.
Next, you will enter the commands for the calcDays() function. The first line stores the
January 1, 2015 date in the newYear variable:
newYear = new Date(“January 1, 2015”);
Using 2015 as the year is only a temporary step. The end goal is to create a Date object
for January 1 st of the year after the current date (whatever that may be). You can deter-
mine this value by extracting the year value from the currentDate variable and adding
1 to it using the following command:
nextYear = currentDate.getFullYear() + 1;
You'll then use the setFullYear() method to change the year of the newYear Date
object to the coming year as follows:
newYear.setFullYear(nextYear);
With the newYear variable now containing a date matching January 1 st of the coming
year, the following command calculates the time difference between that New Year's Day
and the current day:
days = newYear - currentDate;
However, because JavaScript measures time difference in milliseconds, not days, the
days variable stores the number of milliseconds between the current date and time and
the next New Year's Day. To express this value in days, you need to divide the difference
by the number of milliseconds in one day. Because 1000 milliseconds are in one second,
60 seconds are in one minute, 60 minutes are in one hour, and 24 hours are in one day,
the revised expression becomes:
days = (newYear - currentDate)/(1000*60*60*24);
 
Search WWH ::




Custom Search