Click or drag to resize
Json.NETDateTimeZoneHandling setting
 

This sample uses the DateTimeZoneHandling setting to control how DateTime and DateTimeOffset are serialized.

Sample
Types
1public class Flight
2{
3    public string Destination { get; set; }
4    public DateTime DepartureDate { get; set; }
5    public DateTime DepartureDateUtc { get; set; }
6    public DateTime DepartureDateLocal { get; set; }
7    public TimeSpan Duration { get; set; }
8}
Usage
 1Flight flight = new Flight
 2{
 3    Destination = "Dubai",
 4    DepartureDate = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Unspecified),
 5    DepartureDateUtc = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Utc),
 6    DepartureDateLocal = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Local),
 7    Duration = TimeSpan.FromHours(5.5)
 8};
 9
10string jsonWithRoundtripTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
11{
12    DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind
13});
14
15Console.WriteLine(jsonWithRoundtripTimeZone);
16// {
17//   "Destination": "Dubai",
18//   "DepartureDate": "2013-01-21T00:00:00",
19//   "DepartureDateUtc": "2013-01-21T00:00:00Z",
20//   "DepartureDateLocal": "2013-01-21T00:00:00+01:00",
21//   "Duration": "05:30:00"
22// }
23
24string jsonWithLocalTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
25{
26    DateTimeZoneHandling = DateTimeZoneHandling.Local
27});
28
29Console.WriteLine(jsonWithLocalTimeZone);
30// {
31//   "Destination": "Dubai",
32//   "DepartureDate": "2013-01-21T00:00:00+01:00",
33//   "DepartureDateUtc": "2013-01-21T01:00:00+01:00",
34//   "DepartureDateLocal": "2013-01-21T00:00:00+01:00",
35//   "Duration": "05:30:00"
36// }
37
38string jsonWithUtcTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
39{
40    DateTimeZoneHandling = DateTimeZoneHandling.Utc
41});
42
43Console.WriteLine(jsonWithUtcTimeZone);
44// {
45//   "Destination": "Dubai",
46//   "DepartureDate": "2013-01-21T00:00:00Z",
47//   "DepartureDateUtc": "2013-01-21T00:00:00Z",
48//   "DepartureDateLocal": "2013-01-20T23:00:00Z",
49//   "Duration": "05:30:00"
50// }
51
52string jsonWithUnspecifiedTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
53{
54    DateTimeZoneHandling = DateTimeZoneHandling.Unspecified
55});
56
57Console.WriteLine(jsonWithUnspecifiedTimeZone);
58// {
59//   "Destination": "Dubai",
60//   "DepartureDate": "2013-01-21T00:00:00",
61//   "DepartureDateUtc": "2013-01-21T00:00:00",
62//   "DepartureDateLocal": "2013-01-21T00:00:00",
63//   "Duration": "05:30:00"
64// }