Using moment.js to determine if current time (in hour) is between certain hours

Viewed 4491

I am working on a function that'd greet its users with a time-aware greeting (Good Morning, Afternoon, Evening, Night). Here's the script that I've made

import moment from "moment";

function generateGreetings(){
    if (moment().isBetween(3, 12, 'HH')){
        return "Good Morning";
    } else if (moment().isBetween(12, 15, 'HH')){
        return "Good Afternoon";
    }   else if (moment().isBetween(15, 20, 'HH')){
        return "Good Evening";
    } else if (moment().isBetween(20, 3, 'HH')){
        return "Good Night";
    } else {
        return "Hello"
    }
}

$("greet")
.css({
    display: "block",
    fontSize: "4vw",
    textAlign: "center",
    })
.text(generateGreetings() +", name")

But it simply wont work and just returns "Hello". I've also tried using

var currentTime = moment();
var currentHour = currentTime.hour();

and use currentHour to replace moment() inside the function but when I do so the site just dissapears. Hoping anyone here has any insight on what I should do to fix this issue.

3 Answers

You are using moment().isBetween() in a wrong way. You can see the correct method usage from here. For your requirement, no need to use this isBetween method. You can simply get the hour and then check it against the if condition.

You can re-arrange your method like below.

function generateGreetings(){

  var currentHour = moment().format("HH");

  if (currentHour >= 3 && currentHour < 12){
      return "Good Morning";
  } else if (currentHour >= 12 && currentHour < 15){
      return "Good Afternoon";
  }   else if (currentHour >= 15 && currentHour < 20){
      return "Good Evening";
  } else if (currentHour >= 20 && currentHour < 3){
      return "Good Night";
  } else {
      return "Hello"
  }

}

The accepted answer can be simplified a lot; the elses are completely superfluous because of the early returns:

function greeting() {
        const hour = moment().hour();

        if (hour > 16){
            return "Good evening";
        }

         if (hour > 11){
             return "Good afternoon";
         }

         return 'Good morning';
    }

@Thusitha

or you can use

moment().hour()

instead of

moment().format('HH')(
Related