Display message with the condition day of week

I am trying to do a statement using the getDay command, only reads the first line and displays the first IF statement, will not read the else if line. Appreciate any help, new to the forum

<!DOCTYPE html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>JavaScript Example: The Date object</title>
  <script>
    var now  = new Date();        // current date/time
    var hrs  = now.getHours();    // 0 to 23
    var mins = now.getMinutes();
    var secs = now.getSeconds();
	
	
	var weekday = new Array(7);
weekday[0]=  "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var day = weekday[now.getDay()];


    document.writeln("<p>It is " + now + "</p>");
    document.writeln("<p>Hour is " + hrs + "</p>");
    document.writeln("<p>Minute is " + mins + "</p>");
    document.writeln("<p>Second is " + secs + "</p>");
	document.writeln("<p>Today is " + day + "</p>");
    if (hrs < 12) {
      document.writeln("<h2>Good Morning!</h2>");
    } else {
      document.writeln("<h2>Good Afternoon!</h2>");
    }
	if (day = "Sunday") {
      document.writeln("<h2>Sunday</h2>");
    } 
	else if (day = "Monday"){
      document.writeln("<h2>Monday</h2>");
    }
	 else {
      document.writeln("<h2>n</h2>");
    }
  </script>
</head>
<body></body>
</html>

You are using “=” rather than “==” to compare the day of the week. This is what it should look like:

if (day == "Sunday") {
      document.writeln("<h2>Sunday</h2>");
    } 
	else if (day == "Monday"){
      document.writeln("<h2>Monday</h2>");
    }

thank you very much, it worked beautifully
Do I have to use the array? can I just use the else if for the condition and then display a message?

:smiley:

thank you again
the newbie

You don’t need the array if you intend to ask a question like:

if (day == "Sunday") {

You only need it if you intend to use it as a source of weekdays such as:

if(day == weekday[0]){

Using an array would certainly make sense here, so that you don’t have several identical string literals scattered all over the code. And you already got a good idea here:

var day = weekday[now.getDay()];

You can then output the day w/o any ifs like

document.writeln('<h2>' + day + '</h2>')

BTW, you’ll very rarely need to use the Array constructor; instead, you can simply write

var weekday = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday"
]

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.