Kasper Juner
Kasper Juner

Reputation: 952

How to parse date from string using ParseExact?

I'm trying to parse a date from a string formatted as the following "17/9/2020, 13:00:00" as a valid DateTime object, but after trying to use .ParseExact and setting the date pattern i'm getting the error:

String '17/9/2020, 13:00:00' was not recognized as a valid DateTime..

By using .ParseExact i'm trying to do the following:

DateTime.ParseExact(quando.quando, "dd/MM/yyy, HH:mm:ss", null)

Upvotes: 0

Views: 78

Answers (2)

Mong Zhu
Mong Zhu

Reputation: 23732

you have 1 M too much and 1 y too few:

DateTime.ParseExact("17/9/2020, 13:00:00", "dd/M/yyyy, HH:mm:ss", null)

the format MM expects an input of always two digits for the month like 09 (september)

If you take only 1 M it will also parse a 2 digit month like december:

DateTime.ParseExact("17/12/2020, 13:00:00", "dd/M/yyyy, HH:mm:ss", null)

EDIT: taking this from Jon Skeets comment: you should probably also use a single d for days since your date string will likely exhibit the following format "7/9/2020, 13:00:00".

DateTime.ParseExact("7/9/2020, 13:00:00", "dd/M/yyyy, HH:mm:ss", null)

Upvotes: 3

Sergey Vishnevskiy
Sergey Vishnevskiy

Reputation: 443

Your format isn't correct. See an example here: https://dotnetfiddle.net/2ppjvX

You should use this format "dd/M/yyyy, HH:mm:ss". "MM" expects 2 digist like "09". Also 4 "y" symbols are required.

Upvotes: 0

Related Questions