3

I need parse datetimeoffsets from strings of multiple formats. One of the strings that fail is: 08/12/1992 07.00.00 -05:00

Now when I try to parse this, I use:

DateTimeOffset.ParseExact("08/12/1992 07.00.00 -05:00", "dd/MM/yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture)

Which gives a FormatException:

"String was not recognized as a valid DateTime."

I can also try to add delimiters in the separators:

DateTimeOffset.ParseExact("08/12/1992 07.00.00 -05:00", "dd'/'MM'/'yyyy HH':'mm':'ss zzz", CultureInfo.InvariantCulture)

...or other permutations of small/capital letter or separators, but I get the same error.

Can anyone tell me why the ParseExact lines above do not work, and how to correct them?

EDIT: I tried using a LINQ query to replace the colon with dots (: -> .). Apparently that did not work correctly - thanks for the replies.

1
  • That doesn't look like a culture invariant date time string. Commented Sep 28, 2015 at 14:42

2 Answers 2

10

Your actual date (actually time) string delimits the hours from the minutes from the seconds with a dot ., so your format must do the same:

DateTimeOffset.ParseExact("08/12/1992 07.00.00 -05:00", 
    "dd/MM/yyyy HH.mm.ss zzz", CultureInfo.InvariantCulture)
//                ^  ^
//                |  |

If you have multiple string formats in your data, you can do something like this:

    public static DateTimeOffset Parse(string str)
    {
        string[] formats =
        {
            "dd/MM/yyyy HH.mm.ss zzz",
            "dd/MM/yyyy HH:mm:ss zzz"
            // ... possibly more ...
        };

        var dto = new DateTimeOffset();
        if (!formats.Any(f => DateTimeOffset.TryParseExact(str, f, CultureInfo.InvariantCulture, DateTimeStyles.None, out dto)))
        {
            throw new ArgumentException("Unrecognized date format");
        }

        return dto;
    }
Sign up to request clarification or add additional context in comments.

Comments

3

In the statement

DateTimeOffset.ParseExact("08/12/1992 07.00.00 -05:00",
                          "dd/MM/yyyy HH:mm:ss zzz",
                          CultureInfo.InvariantCulture)

the format string uses : as separator for the time parts, but the data argument uses . as separator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.