Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 879
Rippo Avatar asked Sep 13 '25 10:09

Rippo


1 Answers

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.

like image 153
L. Kierepka Avatar answered Sep 15 '25 01:09

L. Kierepka