Prevent timezone conversion on deserialization of DateTime value(防止对 DateTime 值的反序列化进行时区转换)
问题描述
我有一个使用 XmlSerializer 序列化/反序列化的类.此类包含 DateTime 字段.
I have a class that I serialize/deserialize using XmlSerializer. This class contains a DateTime field.
序列化时,DateTime 字段由包含与 GMT 的偏移量的字符串表示,例如 2010-05-05T09:13:45-05:00.反序列化时,这些时间将转换为执行反序列化的机器的本地时间.
When serialized, the DateTime field is represented by a string that includes the offset from GMT, e.g 2010-05-05T09:13:45-05:00. When deserialized, these times are converted to the local time of the machine performing the deserialization.
出于不值得解释的原因,我想阻止这种时区转换发生.序列化发生在野外,存在这个类的多个版本.反序列化发生在我控制的服务器上.因此,这似乎最好在反序列化期间处理.
For reasons not worth explaining, I'd like to prevent this timezone conversion from happening. The serialization happens out in the wild, where multiple version of this class exist. The deserialization happens on a server that's under my control. As such, it seems like this would be best handled during deserialization.
除了实现 IXmlSerializable 并手动"完成所有反序列化之外,我怎样才能做到这一点?
How can I make this happen, other than implementing IXmlSerializable and doing all of the deserialization "by hand?"
推荐答案
您可以将其解析为 DateTimeOffset 而不是解析为 DateTime 并使用 DateTimeOffset.DateTime 属性忽略时区.像这样:
Instead of parsing as a DateTime you can parse it as a DateTimeOffset and use the DateTimeOffset.DateTime property to ignore the timezone. Like this:
[XmlIgnore()]
public DateTime Time { get; set; }
[XmlElement(ElementName = "Time")]
public string XmlTime
{
get { return XmlConvert.ToString(Time, XmlDateTimeSerializationMode.RoundtripKind); }
set { Time = DateTimeOffset.Parse(value).DateTime; }
}
这篇关于防止对 DateTime 值的反序列化进行时区转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:防止对 DateTime 值的反序列化进行时区转换
基础教程推荐
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
