Previously I was facing this issue and solved as described in the post
目前,在DayLight Saving实施之后,我发现了如果我选择
的问题 DateTime startDate=new DateTime(2012,1,20); //Eastern Timezone (UTC -5:00)
序列化后将其转换为:
string serializeDate= serializer.Serialize(startDate); //In ticks 20-Jan 2012 05:00AM
反序列化和ToLocalTime()
DateTime afterDeserialize= serializer.Deserialize<DateTime>(serializeDate);
afterDeserialize.ToLocalTime();
直到完成工作:
我取消选中Automatically adjust clock for Daylight Saving Time
。
现在它的序列化添加4:00 hours
(由于夏令时),但ToLocalTime()
减去-5:00 hours
,因为环境夏令时会改变我的对象减去一天的日期。
如何为两次转换注入当前环境夏令时?
答案 0 :(得分:1)
您需要存储时区的偏移量,然后在转换后重新应用它。
要使其动态化(正如您在评论中所述),您可以先获取当前时区:
TimeZoneInfo tzi = TimeZoneInfo.Local;
TimeSpan offset = tzi.GetUtcOffset(myDateTime);
然后做:
DateTime startDate=new DateTime(2012,1,20).Add(offset);
然后序列化后:
DateTime afterDeserialize= serializer.Deserialize<DateTime>(serializeDate);
afterDeserialize.ToLocalTime().AddOffset(offset);