When I deserialize this json string "2020-10-05T07:29:00+00:00" on my local pc to a DateTime object it ends up as 2020-10-05 09:29, where it should be 07:29. The date is specified as local (+00:00) so I don't understand where the extra two hours come from. I tried looking at this question Datetime timezone deserialization but converting the date by using .ToLocalTime() does nothing.
The context is a large json string with airports from an external API with many datetimes, some are UTC some are local times. I need to find the simplest way to deserialize the string which will produce the correct datetimes.
Note that the local time could be anywhere in the world, so it should not depend on the server that runs the application.
Here's a code example using NewtonSoft.Json to deserialize:
static void Main(string[] args)
{
var json =
"{\"UTC\": \"2020-10-05T05:29:00Z\",\"Local\": \"2020-10-05T07:29:00+00:00\" }";
var expected = new DateTime(2020,10,5,7,29,0);
var foo = JsonConvert.DeserializeObject<CustomTime>(json);
Console.WriteLine($"UTC:{foo.UTC} ({foo.UTC.Kind}).\r\nLOC:{foo.Local} ({foo.Local.Kind})");
System.Console.WriteLine(foo.Local.Equals(expected) ? "All good" : "Conversion failed");
}
public sealed class CustomTime
{
public DateTime UTC { get; set; }
public DateTime Local { get; set; }
}
This is my output in my timezone (UTC +2 DaylightSavingTime):
UTC:05-10-2020 05:29:00 (Utc). LOC:05-10-2020 09:29:00 (Local) Conversion failed
Here is a dotnet fiddle https://dotnetfiddle.net/uHLdAh This produces the correct output since the server probably runs GMT.
DateTimeOffset. The values you're receiving are effectivelyDateTimeOffsetvalues anyway (a local time and a UTC offset) so usingDateTimeinstead just loses information and complicates things. (I'd really suggest using my Noda Time library instead to make things clearer, but that's a slightly different matter.)