Datetime function C#

Asked

Viewed 1,640 times

1

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

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

I don’t really like looking for solutions on the Internet, but I had no idea how to solve this issue 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 to me?

3 answers

1

DateTime.Parse 

Here it is transforming your user data entry which is in text(string) format to the date and time formed.

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

Give a read here, it can help you clarify better: https://msdn.microsoft.com/pt-br/library/zdtaw1bw(v=vs.110). aspx

1


Okay, this is the code:

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

Now let’s break it into pieces 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.

0

You can also use the ParseExact when you want to convert a date to 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 are for the value of hours with two digits and scale 0-12 (HH is for the value of hours with two digits and scale 0-24), mm are for minutes, ss the 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
  • 1

    This code is more correct than the code in the question, and its answer is the best in code, but unfortunately it offers no explanation. If you can write about - and mainly explain the difference between h and H for the method ParseExact - will have my vote.

  • @Renan I’m complementing, just a moment

Browser other questions tagged

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