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!
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
@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
– gleisin-dev