DateTime function C # [duplicate]

1

I came across an exercise in which the AM / PM format date should be converted to military format (24h).

So, suppose the user types 07:05:45 PM, the program should return 19:05:45.

I do not like looking for solutions on the internet, but I had no idea how to solve this problem and I came across the following solution:

 Console.WriteLine(DateTime.Parse(Console.ReadLine()).ToString("HH:mm:ss"));

Even searching the internet, I could not understand how this method works. Could you explain?

    
asked by anonymous 24.07.2017 / 20:25

3 answers

1

Okay, here's the code:

Console.WriteLine(DateTime.Parse(Console.ReadLine()).ToString("HH:mm:ss"));

Now let's break it down into parts and see what each command does and how it works:

Console.ReadLine() //Lê uma string do console (input)

DateTime.Parse() //Converte a string para o tipo de variável DateTime

ToString("HH:mm:ss") //Converte a variável DateTime para string novamente, mas agora respeitando os seguintes parâmetros:
                     // "hora:minutos:segundos" (padrão brasileiro / 24h)

Console.WriteLine() //Escreve a string no console (output)

Documentations:

DateTime , DateTime.Parse , ToString , WriteLine and ReadLine .

    
24.07.2017 / 20:37
1
DateTime.Parse 

Here he is transforming his user data entry which is in text format (string) to the date and time format.

Then it returns the Date format for text, already using the format: ToString("HH:mm:ss") which would basically make the text into a date and time format.

Read it here, it might help you clarify further: link

    
24.07.2017 / 20:34
0

You can also use ParseExact when you want to convert a date in a specific format:

  

Usage: DateTime.ParseExact (string value, string format, IFormatProvider)

Format: For your case, we can use the format hh:mm:ss tt where hh is for the value of the two-digit hours and scale 0-12 ( HH is for the hour value with two digits and scale 0-24), mm are for the minutes, ss seconds, and finally the tt for the period (AM / PM).

            string dataPm = "07:01:02 PM";

            DateTime dt24 = DateTime.ParseExact(dataPm, "hh:mm:ss tt", CultureInfo.InvariantCulture);

            string resultado = dt24.ToString();
            //24/07/2017 19:01:02
    
24.07.2017 / 20:38