Darth Veyda Darth Veyda - 3 months ago 26
C# Question

DateTime.TryParse fails at yyyy only

I have a filter field that allows to search by partial or full date that can be entered in different formats - that is, whichever way the user wants to enter it, so TryParseExact doesn't look like the best option.

The problem is that the following code:

DateTime.TryParse(fromDate.Text, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateFromValue)


parses everything but yyyy strings. E.g. "05/1980" and "1980/05" are recognized as {1/05/1980 12:00:00 AM}, but "1980" fails.

I suspect the parser has no way to distinguish between, say, yyyy and ffff when all it gets is a 4-digit sequence, but I still need to get this working. Is there perhaps a more elegant way to do it than

if(!DateTime.TryParse("1980", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
DateTime.TryParseExact("1980","yyyy",CultureInfo.InvariantCulture, DateTimeStyles.None, out date);


or am I doing it the wrong way altogether?

Thank you in advance!

Answer

I think you cannot use DateTime.Parse with just year only, because the month and day are ambiguous. Using DateTime.ParseExact or DateTime.TryParseExact with specific date format works instead.

Your if condition looks wrong to me though, how do you combine the two conditions?

if(!DateTime.TryParse("1980", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
DateTime.TryParseExact("1980","yyyy",CultureInfo.InvariantCulture, DateTimeStyles.None, out date);

should have been:

if(DateTime.TryParse("1980", CultureInfo.InvariantCulture, DateTimeStyles.None, out date) ||
DateTime.TryParseExact("1980","yyyy",CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
// If the first parse success, use that. Otherwise, try to parse the year only with the parseexact.
// Notice the || and the first condition needs to be positive.