Home > Net >  If/Else condition using specific time ranges
If/Else condition using specific time ranges

Time:09-24

I'm trying to formulate an if/else condition with the following criteria using javaScript:

"Good Morning" if the time is between 5:45 am and 11:59:59 am "Good Afternoon" if the time is between 12:00 pm and 05:59:59 pm "Good Evening" if the time is between 6:00 pm and 5:44:59 am

CodePudding user response:

You can use Date and get current hour with getHours function.

const d = new Date(); // get current date
const hour = d.getHours(); // get current hour

if (hour < 12)
  console.log("good morning");
else if (hour < 16)
  console.log("good afternoon");
else if (hour < 24)
  console.log("good evening");
  
 

If you want to work with minutes too. you can use getMinutes function.

const d = new Date(); // get current date
const hour = d.getHours(); // get current hour
const minute = d.getMinutes(); // get current minute

  if (hour < 12 && minute < 59)
    console.log("good morning and time is hour:"   hour   " minute:"   minute);
  else if (hour < 16)
    console.log("good afternoon and time is hour:"   hour   " minute:"   minute);
  else if (hour < 24)
    console.log("good evening and time is hour:"   hour   " minute:"   minute);

CodePudding user response:

If you convert the time to date format you can use getHours:

var d = new Date();
var n = d.getHours();

See how to work with date and time:

https://www.w3schools.com/jsref/jsref_gethours.asp

  • Related