使用JavaScriptSerializer进行序列化日期类型应该注意时区的问题
scriptSerializer在序列化DateTime时,是用刻度来表示的,具体在Json体现为:\/Date(315547200000)\/ 用V进行一个闭包, 括号内为Date的刻度,刻度就是时间滴答滴答经过的毫秒数,刻度计算的赶止时间为:UTC 1970年1月1日午夜开始的,
注意该起止时间是UTC时间,看看以下程序:
Customer cs = new Customer();
cs.BirthDay = new DateTime(1980, 1, 1, 12, 0, 0);
cs.Name = "steven";
cs.Sex = true;
java scriptSerializer js = new java scriptSerializer();
string output = js.Serialize(cs);
Customer cust = js.Deserialize(output, typeof(Customer)) as Customer;
if (cust != null)
{
txtBirthDay.Text = cust.BirthDay.Value.ToString();
}
cs.BirthDay = new DateTime(1980, 1, 1, 12, 0, 0);
cs.Name = "steven";
cs.Sex = true;
java scriptSerializer js = new java scriptSerializer();
string output = js.Serialize(cs);
Customer cust = js.Deserialize(output, typeof(Customer)) as Customer;
if (cust != null)
{
txtBirthDay.Text = cust.BirthDay.Value.ToString();
}
这样处理时会带来一点问题就是,在进行序列化之后的日期不会是原来的 1980-1-1 12:00:00,而是会根据utc时间得来的一个时间,有可能是1979-12-31 4:00:00,这样在界面进行UI展示的时候会带来一致的问题!
其它处理很简单,序列化之前先把本地时间转换来UTC时间,再在反序列之后,把UTC时间转换为本地时间就OK了,看看更改之后代码:
Customer cs = new Customer();
cs.BirthDay = new DateTime(1980, 1, 1, 12, 0, 0).ToUniversalTime();
cs.Name = "steven";
cs.Sex = true;
java scriptSerializer js = new java scriptSerializer();
string output = js.Serialize(cs);
Customer cust = js.Deserialize(output, typeof(Customer)) as Customer;
if (cust != null)
{
txtBirthDay.Text = cust.BirthDay.Value.ToLocalTime().ToString();
}
cs.BirthDay = new DateTime(1980, 1, 1, 12, 0, 0).ToUniversalTime();
cs.Name = "steven";
cs.Sex = true;
java scriptSerializer js = new java scriptSerializer();
string output = js.Serialize(cs);
Customer cust = js.Deserialize(output, typeof(Customer)) as Customer;
if (cust != null)
{
txtBirthDay.Text = cust.BirthDay.Value.ToLocalTime().ToString();
}