Code for Writing the Date and TimeNow let's put this all together. To get the day, month, and year, we use the getDate(), getMonth(), and getYear() methods. To get the hour and the minutes, we use getHours() and getMinutes().
Line-by-Line Analysis of Figure 2-12Here are a few interesting things in this example.
Making Minor AdjustmentsBefore building the strings we will write to the website, we need to make some little adjustments to the date information just collected. Here's how it works:
- Line Yadds 1 to the month because getMonth() thinks January is month 0.
Getting the String RightNow that we've made a few minor adjustments, it's time to build the strings. Line \ builds the string for the date. Here's the wrong way to do it:
var date_string = month + "/" + day + "/" + year;This may look a little funny at first, but it's done so frequently that you'll soon grow used to it. Line ] creates the string to represent the time. It is very similar to \. Line ^ puts \ and ]together to create the string that will be written to the website. Lines \ through ^ could all have been written as one long line:
var date_time_string = "Today is " + month + "/" + day + "/" + year + ". The time is now " + hour + ":" + minutes + ".";However, using three lines makes the code easier for people to read and understand. It's always best to write your code as if other people are going to read it.