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

4

8

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.

Psia answered 29/5, 2020 at 6:14 Comment(0)
P
17

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"
  }

}
Poolroom answered 29/5, 2020 at 6:27 Comment(3)
This works! Thanks a lot mate! I was using it that way because the example there used date directly so I thought it'll also work with hours.Psia
@DavidBudiarto Glad to hear that. :)Poolroom
For the Good Night you need to change the && to ||, I guess...Suborbital
K
3

@Thusitha

or you can use

moment().hour()

instead of

moment().format('HH')(
Kettle answered 29/5, 2020 at 6:32 Comment(0)
C
3

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';
    }
Cuticle answered 14/9, 2020 at 11:58 Comment(0)
I
0

Here's one way to split day times (Morning times and Evening times)

Replace YYYY-MM-DD with the actual date you want to use:

const date = moment("YYYY-MM-DD");
const morningEnd = moment(date).hour(12).minute(0).second(0);
const eveningStart = moment(date).hour(18).minute(0).second(0);

const morningTimes = [];
for (let m = moment(date); m.isBefore(morningEnd); m.add(30, 'minutes')) {
  morningTimes.push(m.format('HH:mm'));
}

const eveningTimes = [];
for (let m = eveningStart; m.isBefore(moment(date).endOf('day')); m.add(30, 'minutes')) {
  eveningTimes.push(m.format('HH:mm'));
}

console.log('Morning times:', morningTimes);
console.log('Evening times:', eveningTimes);
Iluminadailwain answered 8/2, 2023 at 18:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.