JSON使用DateTimeZoneHandling序列化时时区与日期

来源:互联网 发布:php 文件上传原理 编辑:程序博客网 时间:2024/06/05 20:32

1.先创建一个Flight类

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace JSONDemo{    public class Flight    {        public string Destination { get; set; }        public DateTime DepartureDate { get; set; }        public DateTime DepartureDateUtc { get; set; }        public DateTime DepartureLocal { get; set; }        public TimeSpan Duration { get; set; }    }}


2.使用DateTimeZoneHandling序列化日期,指定是否显示时区

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using GongHuiNewtonsoft.Json;namespace JSONDemo{    class Program    {        static void Main(string[] args)        {            Flight flight = new Flight            {                Destination = "Paris",                DepartureDate = new DateTime(2015, 12, 11, 0, 0, 0, DateTimeKind.Unspecified),                DepartureDateUtc = new DateTime(2015, 12, 11, 0, 0, 0, DateTimeKind.Utc),                DepartureLocal = new DateTime(2015, 12, 11, 0, 0, 0, DateTimeKind.Local),                Duration = TimeSpan.FromHours(11.267)            };            Console.WriteLine("---------只对本地时间显示时区-------------");            string roundtripTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings            {                DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind            });            Console.WriteLine(roundtripTimeZone);            Console.WriteLine("---------对所有时间显示时区---------------");            string localTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings            {                DateTimeZoneHandling = DateTimeZoneHandling.Local            });            Console.WriteLine(localTimeZone);            Console.WriteLine("----------------不显示时区---------------");            string unspecifiedTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings            {                DateTimeZoneHandling = DateTimeZoneHandling.Unspecified            });            Console.WriteLine(unspecifiedTimeZone);        }    }}


3.运行后的结果

 

JSON源代码下载地址:http://download.csdn.net/detail/lovegonghui/9342751

 

0 0
原创粉丝点击