molnarriso
molnarriso

Reputation: 123

String was not recognized as a valid DateTime because the day of week was incorrect

i have this simple line of code :

DateTime.ParseExact("Mon 7:00 PM", "ddd h:mm tt", CultureInfo.InvariantCulture)

If you run this code, 6 days in a week,it will throw this exception :

System.FormatException: String was not recognized as a valid DateTime because the day of week was incorrect.

If you run it on Monday, it will run OK. Is there any way to parse that string correctly ?

Upvotes: 3

Views: 1458

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391276

Unfortunately, DateTime.Parse(Exact) will always return a complete DateTime, complete with a date.

If you ommit any parts detailing the date, it will default to todays date. 6 out of 7 days each week, that will not match the pattern that states monday, and that's why you get that exception.

ParseExact will not attempt to find a matching DateTime value.

For instance, if you run this:

ParseExact("Mon 30.03", "ddd dd.MM", culture)

it will work this year, because 30th of March 2020 is a Monday. However, in 2021, 30th of a March will be on a Tuesday, and thus it will fail again. ParseExact will not try to find a matching year that would have 30th of March on a Monday, and it's the same thing with just specifying Monday. It will not try to figure out which Monday you're talking about.

In short, you will need to find a different way of doing this.

I guess you should step back from ParseExact, and ask yourself, how exactly should "Mon 30.03" be translated into a specific date in a specific year. What is the logic. Then you can try to find the right method to call, or most likely, write the code to do it.

Upvotes: 7

Related Questions