Comparing two times in javascript

I need to run some logic if the current time is for the following cases

  • less than 7 am
  • between 7 am and 9 am.
  • between 9 am and 7 pm
  • more than 7 pm

I'm having a hard time figuring out how I can see if the current time is between the interval:

if(currentHour < 7){
    console.log("Time is before than 7 am :" + 0 );
}
else if (currentHour > 19){
    console.log("Time is after than 7 pm :" + 12148 );
}
else if(//Compare between the hours)

      

Please help with the relevant code.

+3


source to share


3 answers


if (currentHour >= 7 && currentHour <=19) {

}

      



+1


source


Try the following code. The getHours()

class method Date

returns the current hour in 24 hour format. ( 4 PM

- 16

, 7 PM

- 19

etc.)



var currentHour = new Date().getHours();

if (currentHour < 7) {
   console.log("less than 7 am");
}

if (currentHour >= 7 && currentHour <=9) {
   console.log("between 7am and 9 am");
}

if (currentHour >= 9 && currentHour <= 19) {
   console.log("between 9am and 7pm");
}

if (currentHour > 19) {
   console.log("greater than 7pm");
}

      

+1


source


If you were dealing with a single spacing, you can use logical AND ( &&

) like this:

if(currentHour >= 7 && currentHour <= 9) {...}

      

Since you are dealing with multiple contiguous intervals, you can simplify your logic with operators else

, because they will not be executed if the previous condition is if

true:

if(currentHour < 7) { //less than 7am
}
else if(currentHour <= 9) { //between 7am and 9am
}
else if(currentHour <= 19) { //between 9am and 7pm
}
else { //greater than 7pm
}

      

(You may need to change <

or <=

depending on whether you want to include or exclude.)

+1


source







All Articles