C# JavaScriptSerializer and DateTime.MinValue crossing timezones

主宰稳场 提交于 2020-01-05 08:14:10

问题


Given that I have a client and a server, and a class like this:

Client side: (TimeZone: UTC -8)

class Foo {
      public int a;
      public DateTime MyTime { get; set; }
    }

var serialized = new JavaScriptSerializer().Serialize(new Foo { a = 1 });
// Send serialized to server

Server side: (TimeZone UTC-4)

// Receive JSON
var deserialized = new JavaScriptSerializer().Deserialize<Foo>(serialized);
if (deserialized.MyTime == DateTime.MinValue) {
  // dostuff
}

My problem here is that JavaScriptSerializer.Serialize(foo), does MyTime.MinValue.ToUniversalTime() which gives me 1. january 0001 08:00:00. Next when I deserialize on the server side, it sees 8 hours over DateTime.MinValue and the if test fails. I also cannot do to localtime, because the server and client are not in the same timezone, so localtime would give me 1. january 0001 04:00:00.

In the end of this I have to questions:

  1. What is the best way to handle this given that JavaScriptSerializer() does the call .ToUniversalTime(). My current approach is to just check a timerange around year 0.
  2. Given that we have DateTime.MinValue, should one not expect this value to always be exactly that. Should not the DateTime.MinValue.ToUniversalTime() be equal to DateTime.MinValue? Basically I am asking if there should be an explicit if check looking for DateTime.MinValue in all conversion routines.

Thanks.

JavaScriptSerializer: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
DateTime: http://msdn.microsoft.com/en-us/library/system.datetime.aspx


回答1:


Just pass them around as strings instead of DateTimes. yyyy-MM-dd hh:mm:ssZ will make it culture-neutral and cast it to UTC, which will ignore all time zones. This is used in the C# DateTime as code u.




回答2:


Use DateTimeOffset instead of DateTime. It looks like the serializer serializes the struct as follows:

{"a":1,"MyTime":"\/Date(-62135596800000)\/"}

This means that this string can be deserialized by either a DateTime and DateTimeOffset field on the server side. It looks like both of those deserialize the above string to midnight, so I'm assuming that the deserializer interprets the number as a +00:00 offset as it comes off the wire.



来源:https://stackoverflow.com/questions/16917640/c-sharp-javascriptserializer-and-datetime-minvalue-crossing-timezones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!