Customize message by time

5

I wanted to customize the greeting message depending on the time.

Ex:

Hora menor que 12h.
"Bom dia"

Hora menor que 18h.
"Boa tarde"

I made with if and else but wanted a better method.

//Pegando a hora
int hora = DateTime.Now.Hour;

#region saudação
//Personalizando a saudação
if (hora <= 11)
{
    Console.WriteLine("Bom dia " + nome + "!");
}
else if (hora <= 17)
{
    Console.WriteLine($"Boa tarde {nome}!");
}
else if (hora <= 23)
{
    Console.WriteLine($"Boa noite {nome}!");
}
else if (hora <= 5)
{
    Console.WriteLine($"Boa madrugada {nome}!");
}
#endregion
    
asked by anonymous 28.03.2017 / 15:19

1 answer

5

You can do this:

using System;

public class Program {
    public static void Main() {
        int hora = DateTime.Now.Hour;
        var nome = "João";
        var saudacoes = new string[] { "Boa madrugada", "Bom dia", "Boa tarde", "Boa noite" };
        Console.WriteLine($"{saudacoes[hora / 6]} {nome}!");
    }
}

See running on .NET Fiddle . And at Coding Ground . Also I put it in GitHub for future reference .

    
28.03.2017 / 15:32