Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

How to convert DateTime of type DateTimeKind.Unspecified to DateTime.Kind.Utc in C# (.NET)

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. How do I modify the Kind property of a DateTime so that it's UTC and not Unspecified? I don't want to change the time or date. So for example, a date of April 1st 2013, 9:05 am with its Kind property of "Unspecified" should become a datetime of April 1st 2013, 9:05 UTC.

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

  1. Are values necessarily returned from Sql Server Compact as "Unspecified"? Inside Sql Server Compact, they are being stored as type (datetime, not null). Looking at the code, it appears they are just put in the database, but there are no provisions to mark them as UTC or anything. Is there a better way to handle things? Is there a slick way to ensure the DateTimes come out of SQL Compact as 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

question from:https://stackoverflow.com/questions/40272749/how-to-convert-datetime-of-type-datetimekind-unspecified-to-datetime-kind-utc-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

About SpecifyKind() method from MSDN:

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...