Parsing a DateTimeOffset string in C#

11,443

Solution 1

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;
    }

Solution 2

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.

Share:
11,443
Admin
Author by

Admin

Updated on June 15, 2022

Comments

  • Admin
    Admin almost 2 years

    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.