简体   繁体   中英

Datetime in json string is getting converted to localtime

Why is the datetime+offset is getting converted to localtime+offset when convert the json string to Jobject.

Here is the code.

string dataValue = @"{""Time"":""2016-07-15T20:03:41+08:00""}";
JObject json = JObject.Parse(dataValue);
Console.Write(json.ToString());

Output:

{
  "Time": "2016-07-15T17:33:41+05:30"
}

Expected Output:

{
  "Time": "2016-07-15T20:03:41+08:00"
}

By default it will be using the local time, but you can override the default settings:

var dataValue = @"{""Time"":""2016-07-15T20:03:41+08:00""}";

var jsonSerializerSettings = new JsonSerializerSettings
{
    DateTimeZoneHandling = DateTimeZoneHandling.Utc
};

var json = JsonConvert.DeserializeObject<JObject>(dataValue, jsonSerializerSettings);

If you don't care about the date being converted to a DateTime type, you can tell Json.NET to just ignore dates and parse the value as a string :

var dataValue = @"{""Time"":""2016-07-15T20:03:41+08:00""}";

var jsonSerializerSettings = new JsonSerializerSettings
{
    DateParseHandling = DateParseHandling.None
};

var json = JsonConvert.DeserializeObject<JObject>(dataValue, jsonSerializerSettings)

In such a way it will stay exactly as your input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM