118Part IIJavaScript (Web design software) TutorialListing 10-1:Date Object Calculations Date Calculation
118Part IIJavaScript TutorialListing 10-1:Date Object Calculations
Today is:Next week will be: In the Body portion, the first script runs as the page loads, setting a global variable (today) to the current date and time. The string equivalent is written to the page. In the second Bodyscript, the document.write()method invokes the nextWeek()function to get a value to dis- play. That function utilizes the todayglobal variable, copying its millisecond value to a newvariable: todayInMS. To get a date seven days from now, the next statement adds the numberof milliseconds in seven days (60 seconds times 60 minutes times 24 hours times seven daystimes 1000 milliseconds) to today s millisecond value. The script now needs a new Dateobject calculated from the total milliseconds. This requires invoking the Dateobject con- structor with the milliseconds as a parameter. The returned value is a Dateobject, which isautomatically converted to a string version for writing to the page. To add or subtract time intervals from a Dateobject, you can use a shortcut that doesn trequire the millisecond conversions. By combining the date object s set and get methods, youcan let the Dateobject work out the details. For example, in Listing 10-1 you could eliminatethe function entirely, and let the following two statements in the second Body script obtainthe desired result: today.setDate(today.getDate() + 7); document.write(today); Because JavaScript tracks the date and time internally as milliseconds, the accurate dateappears in the end, even if the new date is into the next month. JavaScript automaticallytakes care of figuring out how many days there are in a month as well as in leap years. Many other quirks and complicated behavior await you if you script dates in your page. Aslater chapters demonstrate, however, the results may be worth the effort.
Note: In case you are looking for affordable and reliable webhost to host and run your business application check Vision ftp web hosting services