如何在C#(.NET)中将类型为DateTimeKind.Unspecified的DateTime转换为DateTime.Kind.Utc [英] How to convert DateTime of type DateTimeKind.Unspecified to DateTime.Kind.Utc in C# (.NET)

查看:1123
本文介绍了如何在C#(.NET)中将类型为DateTimeKind.Unspecified的DateTime转换为DateTime.Kind.Utc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了很多DateTimes的C#代码,其中Kind属性是DateTimeKind.Unspecified。这些被输入到Datetime.ToUniversalTime()中,它返回一个UTC日期时间(在我的情况下,它增加了7个小时)。这就是ToUniversalTime()的工作方式;参见MSDN。
问题是这些日期时间实际上已经在UTC时间中。它们被从SQL Server Compact 4.0数据库中拉出。它们存储在UTC中。我的主要问题是:

I've inherited C# code that has an awful lot of DateTimes where the Kind property is DateTimeKind.Unspecified. These are fed into Datetime.ToUniversalTime() which gives back a UTC datetime (it adds 7 hours in my case). This is how ToUniversalTime() works; see MSDN. The problem is that these DateTimes are in fact already in UTC time. They are pulled out of a SQL Server Compact 4.0 database. They were stored there in UTC. My main question is:


  1. 如何修改DateTime的Kind属性,使其为UTC而不是未指定?我不想更改时间或日期。因此,例如,日期为2013年4月1日上午9:05且其Kind属性为未指定的日期应成为2013年4月1日9:05 UTC的日期时间。

如果我沉迷于后续问题,那就是:

If I could be indulged with a follow up question(s), it would be:


  1. 是否必须从Sql Server Compact中以未指定的形式返回值?在Sql Server Compact内部,它们被存储为类型(日期时间,不为null)。查看代码,似乎它们只是放在数据库中,但是没有规定将它们标记为UTC或其他任何内容。有更好的处理方式吗?是否有一种巧妙的方法可以确保DateTimes以SQL格式作为UTC出现?

请告诉我是否可以提供更多详细信息。我是该代码基础的新手,但仍然可以动脑子,所以我很难完美地描述问题。

Please let me know if I can provide more details. I'm new to this code base and still getting my brain around it, so I'm having trouble describing the problem perfectly.

Dave

推荐答案

您可能需要这样的东西吗?

Do you maybe need something like this:

var unspecified = new DateTime(2016, 12, 12, 10, 10, 10, DateTimeKind.Unspecified);
var specified = DateTime.SpecifyKind(unspecified, DateTimeKind.Utc);

关于中的 SpecifyKind()方法href = https://msdn.microsoft.com/zh-cn/library/system.datetime.specifykind(v=vs.110).aspx rel = noreferrer> MSDN

About SpecifyKind() method from MSDN:


SpecifyKind方法使用指定的kind参数和原始时间值创建一个新的DateTime对象。

The SpecifyKind method creates a new DateTime object using the specified kind parameter and the original time value.

它将创建新的对象,新的Kind和相同的时间值。您无法更改现有对象的种类,需要创建具有相同值和不同种类的新对象。

It will create new object, new Kind and same time value. You cannot change Kind of existing object, you need to create new one with same values and different Kind.

关于其他问题,这里的 SQL Compact 。这是关于 DateTimeOffset的问题。看起来它在Sql Compact中尚不支持。

Regarding to other question here are supported types in SQL Compact. And here is issue regarding to DateTimeOffset. It looks like that it is not supported yet in Sql Compact.

这篇关于如何在C#(.NET)中将类型为DateTimeKind.Unspecified的DateTime转换为DateTime.Kind.Utc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆