简体   繁体   English

序列化:DateTime.Now VS DateTime 来自数据库

[英]Serialization: DateTime.Now VS DateTime from database

Context: I'm serializing some data that includes a date of which I need to display milliseconds.上下文:我正在序列化一些数据,其中包含我需要显示毫秒的日期。 I'm using a XmlSerializer to write an XML file.我正在使用 XmlSerializer 编写 XML 文件。 I'm taking some data from a database using a DataTable.我正在使用 DataTable 从数据库中获取一些数据。

What I'm actually doing: I cast the date in this way我实际上在做什么:我以这种方式投射日期

CDate(dr("MyDate")).ToUniversalTime()

But once serialized this does not includes milliseconds.但是一旦序列化,这不包括毫秒。

While trying some workarounds I've found out that serialize in the same way在尝试一些解决方法时,我发现以相同的方式进行序列化

DateTime.Now.ToUniversalTime()

does includes milliseconds.确实包括毫秒。

Actual question: what should I do to include milliseconds while serializing dr("MyDate")?实际问题:我应该怎么做才能在序列化 dr("MyDate") 时包含毫秒?

Please note that answers in VB.NET or C# are both well accepted.请注意 VB.NET 或 C# 中的答案都被广泛接受。

Have you checked, what CDate contains?你有没有检查过,CDate 包含什么? For exmaple Definition of CDate shows that CDate contains only seconds, not milliseconds.例如CDate 的定义显示 CDate 只包含秒,而不是毫秒。 When the original time in the database is stored in text format (with milliseconds) you should use DateTime.TryParseExact(...) to get the complete time value.当数据库中的原始时间以文本格式(以毫秒为单位)存储时,您应该使用 DateTime.TryParseExact(...) 来获取完整的时间值。 Otherwise, when the database itself uses another DateTime-class, you should use this type directly to convert to datetime.否则,当数据库本身使用另一个 DateTime-class 时,您应该直接使用该类型转换为 datetime。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM