0

I always find it difficult to deal with dates. their conversion formats culture etc cause trouble here and there. Although, Convert.ToDateTime, DateTime.Parse and DateTime.TryParse are straight forward where the last one is my most favorite until I stumbled upon an issue with my application where dates are returned as string and values are not coherent (Some starts with Day while other with Month). DateTime.TryParse just don't work when date is starting with 'Month'. e.g. following statement will return null as Month is appearing first in string

DateTime.TryParse("09/26/2011 14:45:00", out dtout) ? dtout : (DateTime?)null

And following statement will be parsed as expected as it has 'Day' appearing first

DateTime.TryParse("12/03/2012 14:30:00", out dtout) ? dtout : (DateTime?)null

I know date string manipulation will not be a good idea especially when no one knows what string is starting with. Is there any way around by applying the culture info or something that I can use to align the string format before do the TryParse?

Learning Curve
  • 1,449
  • 7
  • 30
  • 60

1 Answers1

4

Well, you can use DateTime.TryParseExact with a string[] of allowed formats:

string[] validDateTimeFormats = {"MM/dd/yyyy HH:mm:ss", "dd/MM/yyyy HH:mm:ss" };
DateTime dt;
bool validDate1 = DateTime.TryParseExact("09/26/2011 14:45:00", validDateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
bool validDate2 = DateTime.TryParseExact("12/03/2012 14:30:00", validDateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

But that doesn't solve the core issue, how do you know what is the correct date if both formats can be used to parse the date. Does the date start with the month or with the day?

For example:

bool validDate3 = DateTime.TryParseExact("01/05/2012 14:30:00", validDateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

This will parse to January 5(because that format is the first in the array) which seems to be correct, but it could also be the first may.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939