0

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?

11
  • How do you know it uses Regex in the first place? Commented Feb 22, 2016 at 3:53
  • More or less impossible to do it correctly (as there is no way to distinguish mm/dd/yyyy from dd/mm/yyyy), but there are plenty suggestions on SO (one linked as duplicate, more can be found bing.com/search?q=c%23+parse+date+unknown+format) Commented Feb 22, 2016 at 4:12
  • The DateTime struct doesn't have an internal DateTime "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? Commented Feb 22, 2016 at 4:12
  • Just because DateTimeParse.cs Commented Feb 22, 2016 at 4:12
  • @Enigmativity i hoping there is a way to find the format specifier to exactly parse datetime string in a raw text file using DateTime.ParseExact. Commented Feb 22, 2016 at 4:44

1 Answer 1

0

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));
}
Sign up to request clarification or add additional context in comments.

4 Comments

guessing regex is not a smart way of doing this.
So what is 01022015? January 2nd 2015? Or is it February 1st 2015??
@Syler needs to figure it out between his program and the library that provides these strings.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.