DateTime.ToString() not converting time

Looks like time is automatically getting changed during conversion. My input is 17:15:25. However, it gets converted to 13:15:25 What could be the reason?

string testDate = Convert.ToDateTime("2016-03-24T17:15:25.879Z")
                         .ToString("dd-MMM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);

The result I get for testDate is : 24-Mar-2016 13:15:25

Jon Skeet
people
quotationmark

The Z in your input indicates a UTC time, but the default behaviour of Convert.ToDateTime is to convert the result to your local time. If you look at the result of Convert.ToDateTime("2016-03-30T17:15:25.879Z").Kind you'll see it's Local.

I would suggest using DateTime.ParseExact, where you can specify the exact behaviour you want, e.g. preserving the UTC time:

var dateTime = DateTime.ParseExact(
    "2016-03-30T17:15:25.879Z",
    "yyyy-MM-dd'T'HH:mm:ss.FFF'Z'",
    CultureInfo.InvariantCulture,
    DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
Console.WriteLine(dateTime);      // March 30 2016 17:15 (...)
Console.WriteLine(dateTime.Kind); // Utc

You can then convert that value to a string however you want to.

Of course I'd really suggest using my Noda Time project instead, where you'd parse to either an Instant or a ZonedDateTime which would know it's in UTC... IMO, DateTime is simply broken, precisely due to the kind of problems you've been seeing.

people

See more on this question at Stackoverflow