Rippo
Rippo

Reputation: 22424

Deserilize date keeping local time

Json dates are hard and the conversion seems to be escaping me. It seems to lose the time part inside the conversion.

I have the following Json Microsoft date being returned from an API. I know and can confirm the date is 5th May 2017 7am

enter image description here

However when deserializing the date using newtonsoft I can get it to retain it timezone information. I have tried all the various settings but cannot work this out.

enter image description here

My code to deserialize looks like this

var settings = new JsonSerializerSettings {
     DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
     DateParseHandling = DateParseHandling.DateTimeOffset,
     DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind
};

items = JsonConvert.DeserializeObject<List<UpcomingMeetingListDto>>(
                    responseContent, settings);

Sure it must be easy I just can fathom it out. I think it must be because the date format in the json has no associated TZ information. Maybe I need a custom date deserilizer to handle this case or set the culture.

I am using Newtonsoft.Json version 9.0.1

Upvotes: 4

Views: 297

Answers (1)

L. Kierepka
L. Kierepka

Reputation: 46

DateTime is deserialized correctly, but it is in GMT. To display the local time you should use ToLocalTime() method.

For example by adding a property to your UpcomingMeetingListDto.

public DateTime LocalMeetingDate => MeetingDate.ToLocalTime();

Try this online epoch converter, it shows you both local and gmt time.

Upvotes: 3

Related Questions