Tony_Henrich
Tony_Henrich

Reputation: 44205

How to stop Json.NET JArray.Parse from changing utc dates?

If I have a JSON string with a property which looks like a UTC date, example: "2017-08-25T16:49:27.777-07:00", Json.NET's JArray.Parse modifies the date to another time zone. Is there a way to disable this? I want the date to stay as is. I tried placing this before the parse

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    DateParseHandling = DateParseHandling.None
};

and it had no effect. The JsonLoadSettings class doesn't have a property for handling dates.

Update
This is happening after I change the timezone in my computer. -7 is PDT. I was trying to test my date conversion using different time zones. The date after changing my computer timezone from Pacific to Eastern, after JArray.Parse it becomes "2017-08-25T19:49:27.753-04:00". This messes up my own date conversion where I am trying to convert from supposedly always utc to local machine time.

Upvotes: 5

Views: 1769

Answers (1)

jasper
jasper

Reputation: 541

I just tested two different approaches, one using JsonConvert.SerializeObject<T> and the other one using JArray.Load(JsonReader). Both approaches work for me, regardless of my local time zone.

var serialized = "[\"2017-08-25T20:57:14.3914448+02:00\",\"2017-08-25T18:57:14.3914448+00:00\"]";

//Using JsonConvert.DeserializeObject
var resultA = JsonConvert.DeserializeObject<IEnumerable<DateTimeOffset>>(serialized);

//Using JArray /w JsonReader
var jsonReader = new JsonTextReader(new StringReader(serialized)){DateParseHandling = DateParseHandling.DateTimeOffset};
var resultB = JArray.Load(jsonReader);

However, I don't understand why you state:

This messes up my own date conversion where I am trying to convert from supposedly always utc to local machine time.

It's obviously not UTC time, so it should not be treated as such. UTC is basically Greenwich time (time zone offset 0), but your date time string is reprensenting a time zone offset of -7 hours.

Upvotes: 4

Related Questions