首页 > 解决方案 > 序列化:来自数据库的 DateTime.Now VS DateTime

问题描述

上下文:我正在序列化一些数据,其中包括我需要显示毫秒的日期。我正在使用 XmlSerializer 来编写 XML 文件。我正在使用 DataTable 从数据库中获取一些数据。

我实际上在做什么:我以这种方式投下日期

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

但是一旦序列化,这不包括毫秒。

在尝试一些解决方法时,我发现以相同的方式进行序列化

DateTime.Now.ToUniversalTime()

确实包括毫秒。

实际问题:在序列化 dr("MyDate") 时我应该怎么做才能包含毫秒?

请注意,VB.NET 或 C# 中的答案都被广泛接受。

标签: c#xmlvb.netdatetime

解决方案


Have you checked, what CDate contains? For exmaple Definition of CDate shows that CDate contains only seconds, not milliseconds. 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. Otherwise, when the database itself uses another DateTime-class, you should use this type directly to convert to datetime.


推荐阅读