HTML and CSS Reference
In-Depth Information
Finally, the getFullYear() method extracts the four-digit year value from the Date
object. The following code stores the value of the current year in the thisYear variable:
thisDate = new Date(“February 24, 2015 14:35:05”);
thisYear = thisDate.getFullYear();
After running this code, the value of the thisYear variable is 2015.
Comparing the getFullYear() and getYear() Methods
As you've seen, the getFullYear() method extracts the year value as a four-digit
number; however, earlier implementations of JavaScript used the getYear() method,
which returns a two-digit year value based on a starting year of 1900. For example, the
getYear() method used with a Date object based on the year 1996 returns the value
96. This approach of returning only the two-digit year value was an example of the
so-called Y2K bug, in which programs that relied on two-digit year values would begin
to show mistakes with the start of the new century in the year 2000. For dates past the
year 2000, the getYear() method returns a three-digit year value, and thus the year
2015 would return the value 115.
You might still encounter the getYear() method in legacy pages. But because
of the inconsistency in how it is applied, it is recommended that you only use the
getFullYear() method to extract and display year values.
Retrieving the Hour, Minute, and Second Values
In addition to methods for extracting date, month, and year values from a Date object,
JavaScript supports similar methods for extracting the hours, minutes, and seconds values
from a Date object. These methods are
date .getSeconds()
date .getMinutes()
date .getHours()
where date is once again a Date object. Note that hours are expressed in 24-hour time,
so the following code stores the value 14 , rather than 2 p.m. , in the thisHour variable:
thisDate = new Date(“February 24, 2015 14:35:05”);
thisHour = thisDate.getHours();
Figure 11-8 summarizes the methods for retrieving date and time values from Date objects.
Search WWH ::




Custom Search