Search code examples
c#datetimeparsingformatexception

TryParse/ParseExact on string fails to convert to format ("dddd dd MMMM") if adding months after the new year


My goal is to convert a string parameter with format 'dddd dd MMMM' into a DateTime object. The string parameter itself is formed from fetching a relative date from today, some months in the future, for example DateTime.Now.AddMonths(5).ToString("dddd dd MMMM");. When using the TryParse/ParseExact method to convert the parameter string back to a DateTime that is after the new year (in this case after January 1st 2019) I get the following error:

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

When I attempt to pass a parameter of the required format before the new year, it is accepted as valid. Could it be something to do with a Leap Year calculation that is needed or is there another reason for this?

Thanks,


Solution

  • It's nothing to do with the year being a leap-year... the reason it's succeeding for dates from this year but failing for dates from next year is that your format doesn't include the year, so .Net is making an assumption that the year is this year, and a day, month-day and month from next year will not parse.

    For example:

    "Saturday 16 March" -> parses without error, since this is valid now, in 2019.

    "Monday 16 March" -> error as described. This is a valid combination of day, month-day and month in 2020, but it's not valid for this year, 2019.