I have a method that (sometimes) takes in a string in the format "dddd MMMM dd"
(Monday January 04) that needs to get parsed into a DateTime. I say sometimes because it may also get passed in "Today"
or "Tomorrow"
as the value.
The code to handle this was simple enough:
if (string.Compare(date, "Today", true) == 0)
_selectedDate = DateTime.Today;
else if (string.Compare(date, "Tomorrow", true) == 0)
_selectedDate = DateTime.Today.AddDays(1);
else
_selectedDate = DateTime.Parse(date);
This worked until halfway through December. Some of you have probably already spotted what went wrong.
This would have failed on any date in the New Year with the error:
"String was not recognized as a valid DateTime because the day of week was incorrect."
It was getting passed "Monday January 04"
which is a valid date for 2010, but not in 2009.
So my question is: Is there any way to set the year either for the current year or the next year? Right now, as a quick and dirty fix, I have this:
if (!DateTime.TryParseExact(date, "dddd MMMM dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _selectedDate))
if (!DateTime.TryParseExact(date + " " + (DateTime.Now.Year + 1), "dddd MMMM dd yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out _selectedDate))
throw new FormatException("That date is not valid.");
So it will try to parse it using the current year, and if it is unsuccessful it will try again using the next year. If it fails after that, it'll just assume it's an invalid date because I only need to worry about 1 year in advance, but if anyone has a more flexible solution, I'd appreciate it. (Note, I don't need to worry about validating the date that gets passed in, it will be valid for either the current or following year).