如何以符合标准的方式序列化 .NET 中的 DateTime 对象
我的目标是使用 .NET DateTime 对象(在 C# 中),并以符合标准的方式将其序列化为字符串(用于 XML)并从中解析。 我想到的具体标准是表示日期和时间的 ISO 8601 标准。
我想要一个易于使用的解决方案(最好是每种方式调用一个方法) 它将在格式的串联版本之间进行转换。 我还想保留本地时区信息。
以下是我想要获取的字符串类型的示例:
2009-04-15T10:55:03.0174-05:00
我的目标 .NET 版本是 3.5。
实际上,几年前我找到了解决此问题的方法,其中涉及自定义格式和 DateTime.ToString(string) 方法。 令我惊讶的是,不存在更简单的符合标准的解决方案。 使用自定义格式字符串以符合标准的方式序列化和解析对我来说有点味道。
My goal is use the .NET DateTime object (in C#) and have that be serialized to and parsed from a string (for use in XML) in a way that is standards compliant. The specific standard I have in mind is the ISO 8601 standard for representing dates and times.
I want an easy to use solution (preferably, one method call each way)
that will convert to and from the concatenated version of the format. I would also like to preserve local time zone information.
Here's an example of the sort of string I'd like to get:
2009-04-15T10:55:03.0174-05:00
My target .NET version is 3.5.
I actually found a solution to this problem several years ago which involves a custom format and the DateTime.ToString(string) method. I was surprised that a simpler standards compliant solution didn't exist. Using a custom format string to serialize and parse in a standards compliant way smells a little to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
幸运的是,有
XmlConvert.ToString()
和XmlConvert.ToDateTime()
可以处理这种格式:(选择适当的序列化模式)
Fortunately, there is
XmlConvert.ToString()
andXmlConvert.ToDateTime()
which handles this format:(pick your appropriate serialization-mode)
dateobj.ToString("s")
将为您提供符合 ISO 8601 的字符串表示形式,然后可以使用DateTime.Parse()
对其进行反序列化dateobj.ToString("s")
will get you an ISO 8601-compliant string representation, which can then be deserialized withDateTime.Parse()
过去几年,.NET 在这方面似乎有了一些改进。 System.Xml.XmlConvert 对象似乎是旨在解决在此背景下出现的一整类需求。 以下函数似乎是专门为以灵活且符合标准的方式解决 DateTime 对象的转换而设计的。
如果您想要保留原始时区信息,以下枚举成员似乎特别有用:
以下是 MSDN 上函数文档的链接:
XmlConvert.ToDateTime(string, System.Xml.XmlDateTimeSerializationMode)
XmlConvert.ToString(DateTime, System.Xml.XmlDateTimeSerializationMode)
It looks like .NET has improved a little in this regard over the past few years. The System.Xml.XmlConvert object seems to be designed to address a whole class of needs that appear in this context. The following functions appear to be designed specifically to address conversion of DateTime objects in a flexible and standards compliant way.
The following enumeration member seems especially useful in the case that you want to preserve the original time zone information:
Here are links to documentation for the functions on MSDN:
XmlConvert.ToDateTime(string, System.Xml.XmlDateTimeSerializationMode)
XmlConvert.ToString(DateTime, System.Xml.XmlDateTimeSerializationMode)
尝试这个:
Try this: