在C#中从T-Sql数据库读取保存为UTC的DateTime

21

我将日期时间以UTC的形式保存在t-sql数据库中,而不是本地时间,即保存后,它失去了它是UTC日期的信息,例如:2011-11-08 00:00:00.000。在C#中从数据库中读取时,它会被读为本地时间而不是UTC时间,例如:在读取dateTime值后,dateTime.ToUniversalTime()会给出一个不同的值。

如何将数据库中的日期时间值作为UTC而不是本地时间读取?或者我应该在t-sql中以本地时间保存?


如果你检查 dateTime.Kind,你会得到什么?它可能是 Unspecified... - Jon Skeet
dateTime.Kind 是 Unspecified。 - hIpPy
保存此日期时间的插入(或更新)查询是什么样子? - Edmund Schweppe
3个回答

31

好的,如果你获得的 DateTime 具有 UnspecifiedKind,你可以直接使用:

DateTime utc = DateTime.SpecifyKind(unspecified, DateTimeKind.Utc);

这种问题只是我不喜欢DateTime原因之一


我不喜欢的事实是,当UTC日期时间值保存在T-SQL数据库中时,时区信息会丢失,并被读取为本地时间。 - hIpPy
2
@hIpPy:不,这很麻烦 - 但基本上这是数据库类型的问题。如果您的数据库支持,可以使用DateTimeOffset - Jon Skeet
它帮助解决了时区的问题。谢谢。 - arif.khan.b

0

属性Kind可以是:本地时间、协调世界时、未指定。如果您只是初始化一个新的DateTime对象,Kind默认设置为本地时间。

// read exact same time from DB, but leave the 'Kind' to be Unspecified
// PS Kind is not local, not utc here
(DateTime)(reader["dbdate"]) 

// read exact same time from DB, but set 'Kind' to be UTC
// if your date in your DB is also utc time, then use this one
DateTime.SpecifyKind((DateTime)(reader["dbdate"]), DateTimeKind.Utc) 

如果你只是初始化一个新的DateTime对象,Kind属性默认设置为Local。不,它的默认值是Unspecified。 - osexpert

0

Jon Skeet的solution对我没用。由于某种原因,DateTime.SpecifyKind(date, DateTimeKind.Utc)返回一个Unspecified类型的DateTime对象。

然而,以下方法可行:

var date = DateTime.Parse("2017-03-07 00:15:2.663"); // Assuming UTC, Kind=Unspecified
date = TimeZoneInfo.ConvertTimeToUtc(date, TimeZoneInfo.Utc); // Assuming UTC, Kind=Utc
var output = Newtonsoft.Json.JsonConvert.SerializeObject(date); // "2017-03-07T00:15:02.663Z"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接