0

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!

Darth Veyda
  • 828
  • 2
  • 12
  • 23

2 Answers2

5

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. 
kurakura88
  • 2,185
  • 2
  • 12
  • 18
  • Good point - I should be more careful when copypasting! Thank you for pointing that out :) In this particular case I would be perfectly okay with TryParse just guessing the missing day and month (e.g. 1st January by default) - if only it could do that :( – Darth Veyda Aug 15 '16 at 02:50
0

If you want partial matches the easiest way is to treat the date as a string and just use string matching instead of depending on date formats.

FloatingKiwi
  • 4,408
  • 1
  • 17
  • 41
  • I've been considering that, but TryParse _mostly_ works, so trying to make it _fully_ work looks really tempting :) – Darth Veyda Aug 15 '16 at 02:49