Search code examples
c#.netdatedatetimeoffset

How to parse this DateTimeOffset?


I'm getting a DateTimeOffset string as "2018-10-16T193850+0200", but I think it's none of the standard formats. Mainly, the "+0200" part is not standard, because it lacks the colon.

What format do I have to specify to parse DateTimeOffsets like this?


Solution

  • You can use ParseExact:

    DateTimeOffset offsetDate = DateTimeOffset.ParseExact(
        "2018-10-16T193850+0200",
        "yyyy-MM-dd'T'HHmmsszzzz",
        DateTimeFormatInfo.InvariantInfo,
        DateTimeStyles.None);
    

    Read: Custom Date and Time Format Strings