Greeting Functions "Good morning, Good afternoon and Good evening"

Asked

Viewed 125 times

1

Today I came across a very interesting topic, which are the greetings "Good morning, Good afternoon and Good night" in Javascript (and among other languages..)

Where in failed attempt to create a simple, small and easy code too "hit me" with some eventualities. Follow the code below:

var h = new Date('May 31, 2021 09:00:00').getHours(); // alterna entre 06, 12, 18, 00
var greetings = ['Boa madrugada', 'Bom dia', 'Boa tarde', 'Boa noite'];

console.log(greetings[h / 6]); // dividindo a hora por 6, seu resultado servirá para encontrar a posição do valor na Array

It had everything to work, but the values of the current hours, between the 6 and 12 (7, 8, 9, ...), the 12 and 18 (13, 14, 15, ...) and the 18 and 00 (19, 20, 21, ...).

The values between them consequently are not found in Array the result of the division by 6 of the current time, unless the Array had their respective values according to the result.

amid:

  • 06 and 12 = Good morning
  • 12 and 18 = Good afternoon
  • 18 and 00 = Good evening
  • 00 and 05 = Good morning

Applying ..

I arrived at this result that somehow "cleaned up" the problem!

const greetingMessage = () => {
  let h = new Date().toLocaleTimeString('pt-BR', {hour: 'numeric', hour12: false}); // formato 24 horas (0-23)
  if (h >= 0 && h <= 5) { // entre meia noite (0h) e 5 da madrugada
    return 'Boa madrugada';
  } else if (h >= 6 && h < 12) { // entre 6 e 11 da manhã
    return 'Bom dia';
  } else if (h >= 12 && h < 18) { // entre meio dia (12h) e 17 (5h) da tarde
    return 'Boa tarde';
  } else if (h >= 18 && h <= 23) { // entre 18 (6h) e 23 (11h) da noite
    return 'Boa noite';
  }
}

console.log(greetingMessage());

but would have somehow more "clean" without requiring the use of so many Ifs/Else?

Obs: the intention is to leave the code with fewer lines possible!

  • 1

    To get the numerical value of the hours, just do new Date().getHours(), which returns the value between 0 and 23. toLocaleTimeString returns a string, which is then automatically converted to number (because of the rules of comparison operators), but if the idea is to compare numbers, then getting the value as number from the start is simpler and recommended

  • @hkotsubo yes yes, thank you for the remark, as it was something in a hurry, really went unnoticed! is until dynamic refactor this variable, the line greatly reduces in terms of number of characters. I will not change the question, I chose to leave this correction in the edition of Augusto Vasques' answer

1 answer

2


Edit:

As reported in the comment of hkotsubo informing that it facilitates the adoption of the Date.prototype.getHours() which returns the time to the specified date, according to the local time.
So lines:

let h = new Date().toLocaleTimeString('pt-BR', { 
   hour: 'numeric',
   hour12: false 
});

Were replaced by:

let h = new Date().getHours();

Some possible refactoring for your code:

  • Using conditional statement if.

const greetingMessage = () => {
  //let h = new Date().toLocaleTimeString('pt-BR', { hour: 'numeric', hour12: false });
  let h = new Date().getHours();
  if (h <= 5) return 'Boa madrugada';
  if (h < 12) return 'Bom dia';
  if (h < 18) return 'Boa tarde';
  return 'Boa noite';
}

console.log(greetingMessage());

const greetingMessage = () => {
  //let h = new Date().toLocaleTimeString('pt-BR', { hour: 'numeric', hour12: false }); 
  let h = new Date().getHours();
  switch (true) {
    case h <= 5: return 'Boa madrugada';
    case h < 12: return 'Bom dia';
    case h < 18: return 'Boa tarde';
    default: return 'Boa noite';
  }      
}

console.log(greetingMessage());

const greetingMessage = () => {
  //let h = new Date().toLocaleTimeString('pt-BR', { hour: 'numeric', hour12: false });
  let h = new Date().getHours();
  return (h <= 5) ? 'Boa madrugada' :
         (h < 12) ? 'Bom dia' :
         (h < 18) ? 'Boa tarde' :
         'Boa noite';
}

console.log(greetingMessage());

  • Using mathematics.

const greetingMessage = () => {
  var greetings = ['Boa madrugada', 'Bom dia', 'Boa tarde', 'Boa noite'];
  //let h = new Date().toLocaleTimeString('pt-BR', { hour: 'numeric', hour12: false });
  let h = new Date().getHours();
  return greetings[(h / 6) >> 0];   //Trunca o resultado da divisão obtendo sempre um inteiro.
}

console.log(greetingMessage());

  • Wonder Augustus!! gave a cool turbine.. I just did not understand the operator’s use >> it would be him "greater than zero"?

  • @gleisin-dev See in the documentation Shift to the right >>. In case it is a hack to truncate a number by scrolling 0(zero) bits to the right, thus returning only the entire part of that number.

  • Could also be return greetings[~~(h / 6)]; or else return greetings[Math.trunc(h / 6)];

  • interesting, I’ll take a look!!

  • 2

    It’s no longer simple to use new Date().getHours()?

  • @hkotsubo, I was focused there on META, now I can give you better attention. You say here let h = new Date().getHours(); yes for sure is a good code enhancement.

  • Yeah, that’s right, that’s right :-)

  • @hkotsubo I’m already doing the editing of all code snippets. Sorry for not giving you attention at first.

  • Problem-free

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.