Previous Page
Next Page

Working with Days

You might want to display a different message to your users if it's a weekend. Script 13.2 tells you how to do it.

Script 13.2. This script figures out if it is a weekday or weekend.

window.onload = initDate;

function initDate() {
     var now = new Date();
     var dtString;

     if (now.getDay() > 0 && now.getDay() < 6) {
        dtString = "Sorry, it's a weekday.";
     }
     else {
        dtString = "Hooray, it's a weekend!";
}

     document.getElementById("dtField"). innerHTML = dtString;
}

To figure out if it is a weekend:

1.
var now = new Date();



Fill the variable now with the current date.

2.
if (now.getDay() > 0 && now. getDay() < 6) {



This extracts the numerical day of the week from the now variable and asks if it is greater than 0 (remember that Sunday is 0). Next the line uses the && operator, which is a logical and (i.e., both parts have to be true), and asks if now is less than 6, which is the number for Saturday.

3.
dtString = "Sorry, it's a weekday.";



If the result of the last expression is greater than 0 and less than 6, it has to be between 1 and 5, which is to say, from Monday to Friday, so the script puts a string to that effect into dtString.

4.
else {
  dtString = "Hooray, it's a weekend!";



If we failed the test in the step 2, it must be a weekend, and we put a string with the happy news in dtString.

5.
document.getElementById("dtField"). innerHTML = dtString;



Finally, we set the innerHTML property of dtField to the value of dtString, just as in the previous example. The result is shown in Figure 13.2.

Figure 13.2. The sad news gets written to the window.



Previous Page
Next Page