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:
If I could be indulged with a follow up question(s), it would be:
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
The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo. ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.
If you store a DateTime object to the DB with a DateTimeKind of either Utc or Local , when you read that record back from the DB you'll get a DateTime object whose kind is Unspecified . Basically, it appears the Kind property isn't persisted.
DateTimeKind Enum (System)Specifies whether a DateTime object represents a local time, a Coordinated Universal Time (UTC), or is not specified as either local time or UTC.
To do this, we will use the FindSystemTimeZoneById() of TimeZoneInfo class. This function takes Id as a parameter to return the equivalent time in timezone passed. In the example below, we are taking the current system time and converting it into “Central Standard Time”. DateTime currentTime = TimeZoneInfo.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With