Search code examples
c#datetimetimezoneutctimestamp-with-timezone

How do I convert "2015-11-06T18:34:07+05:30" string to UTC DateTime object in C#


I need to convert "2015-11-06T18:34:07+05:30" timestamp coming from server to DateTime object in C#.Then I need to convert this DateTime to UTC for comparison during synchronization process.And the time zone in this time stamp can vary.So how do I create a timezone independent functionality to get a UTC DateTime object from this timestamp string.


Solution

  • DateTime dt = DateTime.Parse("2015-11-06T18:34:07+05:30",
                   CultureInfo.InvariantCulture,
                   DateTimeStyles.AdjustToUniversal);
    

    Or:

    DateTime dt = DateTime.ParseExact("2015-11-06T18:34:07+05:30",
                                      "yyyy-MM-dd'T'HH:mm:ssK",
                                      CultureInfo.InvariantCulture,
                                      DateTimeStyles.AdjustToUniversal);
    

    Or:

    DateTimeOffset dto = DateTimeOffset.Parse("2015-11-06T18:34:07+05:30",
                                              CultureInfo.InvariantCulture);
    DateTime dt = dto.UtcDateTime;
    

    Or:

    DateTimeOffset dto = DateTimeOffset.ParseExact("2015-11-06T18:34:07+05:30",
                                                   "yyyy-MM-dd'T'HH:mm:sszzz",
                                                   CultureInfo.InvariantCulture);
    DateTime dt = dto.UtcDateTime;
    

    Of course, there are also the TryParse and TryParseExact variants, if you need validation.

    Personally, I'd recommend keeping it as a DateTimeOffset rather than going back to DateTime.

    There's also Noda Time:

    OffsetDateTimePattern pattern = OffsetDateTimePattern.ExtendedIsoPattern;
    OffsetDateTime odt = pattern.Parse("2015-11-06T18:34:07+05:30").Value;
    DateTimeOffset dto = odt.ToDateTimeOffset();
    DateTime dt = dto.UtcDateTime;