Is it possible to get the DateTime format from DateTime class itself for parsing? We have disparate systems that return datetime in various formats, how to parse them without knowing the exact regex pattern?
1 Answer
Use TryParse and try various formats, starting from the the most popular one. When DateTime is correctly built, TryParse returns true and you can use this DateTime. Else, try another pattern.
For example:
internal DateTime ParseDateString(string dateString)
{
DateTime myDateTime;
var attempt1 = doSomeRegex(dateString);
if (DateTime.TryParse(attempt1, out myDateTime))
{
return myDateTime;
}
var attempt2 = anotherRegex(dateString);
if (DateTime.TryParse(attempt2, out myDateTime))
{
return myDateTime;
}
var attempt3 = lastChanceRegex(dateString);
if (DateTime.TryParse(attempt3, out myDateTime))
{
return myDateTime;
}
throw new ArgumentException($"Error parsing date string: {dateString}", nameof(dateString));
}
4 Comments
Syler
guessing regex is not a smart way of doing this.
mason
So what is
01022015? January 2nd 2015? Or is it February 1st 2015??Amadeusz Wieczorek
@Syler needs to figure it out between his program and the library that provides these strings.
Syler
ya its so convoluted when it is not supposed to be. @mason you are right, its not possible to parse without knowing the format specifier esp in the case of non standard dates. But i think i have found my answer. for unknown dates format specifier needs to be provided for standard dates tryparse works just fine.
DateTimestruct doesn't have an internalDateTime"format". I don't know what you're asking with that. Are you saying that you have a bunch of date/time formatted strings and you'd like to try parse them using a series of possible formats?