简体   繁体   中英

javascript if else statement with timer

I have an 'if else' statement that works. But I'd like to add another condition to it. The statement is below:

function showDateContent(){
 var d=new Date();
  if(d.getDate()>=11&& d.getMonth()+1 == 11){
   //show something
 }else{
   //show something else
    }
  }

showDateContent();

The conditional statement that I am trying to write is like this (below), but it doesn't seem to work. Notice I am trying to get something to happen when the date is between two numbers in the 1st statement, and then I have two more conditional statements similar to my first example.

function showDateContent(){
 var d=new Date();
  if(d.getDate()> 11 && d.getDate()< 13 && d.getMonth()+1 == 11){
   //show something when the date is between 11 and 13
} else if(d.getDate()>=14&& d.getMonth()+1 == 11){
   //show something when the date is equal or past the date of the 14th
  }else{
   //show something else when the date is before the 11th
    }
  }
}

showDateContent();

try using console.log() to print date and month which your browser is having and then use if and else statements based on it..

because here in India it is 13-11-2017 and you haven't handled anything for date = 13 so it is going in last else part when I am trying your code which is

function showDateContent(){
 var d=new Date();
console.log(d.getDate(), d.getMonth());   // prints 13   10
  if(d.getDate()> 11 && d.getDate()< 13 && d.getMonth()+1 == 11){
   console.log("show something when the date is between 11 and 13");
  } else if(d.getDate()>=14&& d.getMonth()+1 == 11){
   console.log("show something when the date is equal or past the date of the 14th");
  } else {
   console.log("how something else when the date is before the 11th");
   }
}

showDateContent();

but when I do d.getDate()<= 13 so it goes in given if which is in below code

if(d.getDate()> 11 && d.getDate()<= 13 && d.getMonth()+1 == 11){
 console.log("show something when the date is between 11 and 13");
}

also there was an extra "}" bracket in last of your code which wasn't required.

You should first check if the month is correct

if(d.getMonth() + 1 == 11) {
...
}

Then you have the 3 cases:

if(d.getDate() < 11) {

} else if(d.getDate() > 13) {

} else {

}

So you get this:

 if(d.getMonth() + 1 == 11) {

       if(d.getDate() < 11) {

       } else if(d.getDate() > 13) {

       } else {

       }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM