2

I have a JSON file which I have deserialized into a class I created called MyType

JsonConvert.DeserializeObject<MyType>(json);

One of the JSON properties is Time which is expressed in UTC. I take this UTC Time and convert it into a DATETIME object

DateTime timestamp = DateTime.ParseExact(
    JsonTime, "o", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);

The above works fine when the UTC Time is: 2014-06-25T00:30:07.9289078+00:00

But pukes on : 2014-06-24T00:31:08.62124+00:00

I suspect it's most likely because of the missing trailing "0"s before the "+"

I was playing around with JSON.net and was trying to use the Jtoken.Parse method which seems to be doing what I want.

var t = Newtonsoft.Json.Linq.JToken.Parse(
      @"{ ""x"": ""2014-06-24T00:31:08.62124+00:00"" }").Value<DateTime>("x");

How is JToken.Parse converting this UTC Time correctly and how can I use it in JsonConvert.DeserializeObject<MyType>(json); ?

I tried to set this

public static JsonSerializerSettings JsonSerializerSettings1
{
  get
  {
     return new JsonSerializerSettings { DateParseHandling = DateParseHandling.DateTime};
  }
}
.......
return JsonConvert.DeserializeObject<MyType>(json, JsonSerializerSettings1);

It still does not convert the UTC into date time during deserialization

1 Answer 1

9

Did you try setting DateFormatHandling to IsoDateFormat and DateTimeZoneHandling to Utc?

class Program
{
    static void Main(string[] args)
    {
        string json = @"{ ""Date"": ""2014-06-24T00:31:08.62124+00:00"" }";

        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
            DateTimeZoneHandling = DateTimeZoneHandling.Utc
        };

        MyType obj = JsonConvert.DeserializeObject<MyType>(json, settings);

        Console.WriteLine(obj.Date.ToString());
    }
}

class MyType
{
    public DateTime Date { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.