Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add timezone offset to JSON.NET serialization?

Tags:

c#

json.net

My DateTimePicker is bound to property:

    picker.DataBindings.Add("Value", this, "EventDate");
    ...
    private DateTime eventDate;
    public DateTime EventDate
    {
        get
        {
            var offset = TimeZoneInfo.Local.GetUtcOffset(eventDate);
            string json = JsonConvert.SerializeObject(eventDate, Formatting.Indented);
            Console.WriteLine("get: {0} --- {1}", json, offset);
            return eventDate;
        }
        set
        {
            var offset = TimeZoneInfo.Local.GetUtcOffset(value);
            string json = JsonConvert.SerializeObject(value, Formatting.Indented);
            Console.WriteLine("set: {0} --- {1}", json, offset);
            eventDate = value;
        }
    }

Whenever data binding is to set the property, I've got the following result:

set: "2015-08-03T16:06:59" --- 04:00:00
get: "2015-08-03T16:06:59" --- 04:00:00

The code in get/set only for debug purposes. The whole class is serialized along with EventDate property.

How can I modify DateTime variable and/or json serializer in order to include timezone offset such as:

"2014-08-03T16:06:59.8708232+04:00"

Strange thing is if I create brand new DateTime object and assign to DateTime.Now without binding, JSON.NET will append timezone offset to it. Can't figure out what is the difference.

like image 805
Pablo Avatar asked Aug 03 '14 12:08

Pablo


1 Answers

I use this.

It works very well.

JsonConvert.SerializeObject(object, new JsonSerializerSettings()
{
    DateFormatHandling = DateFormatHandling.IsoDateFormat,
    DateTimeZoneHandling = DateTimeZoneHandling.Local
});
like image 102
CMS Avatar answered Oct 21 '22 13:10

CMS