11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Converting this last example to a more usable value isn‘t difficult and is discussed next.<br />

Manipulating Dates<br />

To hide the fact that Date objects store values as millisecond offsets from the epoch, dates are<br />

manipulated through the methods they provide. That is, Date values are set and retrieved by<br />

invoking a method rather than setting or reading a property directly. <strong>The</strong>se methods handle the<br />

conversion of millisecond offsets to human-friendly formats and back again for you<br />

automatically. <strong>The</strong> following example illustrates a few of the common Date methods:<br />

var myDate = new Date();var year = myDate.getYear();year = year + 1;myDate.setYear(year);<br />

alert(myDate);<br />

This example gets the current date and adds one year to it. <strong>The</strong> result is shown here:<br />

<strong>JavaScript</strong> provides a comprehensive set of get and set methods to read and write each field of<br />

a date, including getDate(), setDate(), getMonth(), setMonth(), getHours(), setHours(),<br />

getMinutes(), setMinutes(), getTime(), setTime, and so on. In addition, UTC versions of all<br />

these methods are also included: getUTCMonth(), getUTCHours(), setUTCMonth(),<br />

setUTCHours(), and so forth. One set of methods requires a special comment: getDay() and<br />

setDay(). <strong>The</strong>se are used to manipulate the day of the week that is stored as an integer from 0<br />

(Sunday) to 6 (Saturday). An example that illustrates many of the common Date methods in<br />

practice is shown here (the results are shown in Figure 7-1):<br />

Figure 7-1: Common Date functions in action<br />

var today = new Date();

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!