Convert string to Datetime with . Parseexact()

Asked

Viewed 133 times

1

I am trying to receive a string typed by the user in the format "dd/MM/yyyy hh:mm", but whenever I use a date above 12:59 the following error occurs:

System.Formatexception: 'String '25/06/2018 13:00' was not recognized as a Valid Datetime.'

Code:

DateTime inicio = DateTime.ParseExact(Console.ReadLine(), "dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture);

1 answer

3


The hour format for 24h is "HH", capitalized, using this will work:

DateTime inicio = DateTime.ParseExact(Console.ReadLine(), "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);

The "hh" format is for 12h only, so you have this error.

See here working: https://dotnetfiddle.net/0g6fXE

But in your example, which is trying to read the entered value, you should first receive the entered value in a variable and validate the format before trying to convert.

Browser other questions tagged

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