Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading DateTime saved in UTC from T-Sql database in C#

I'm saving datetime in t-sql db as UTC and not local time i.e after saving, it loses that it is UTC date ex: 2011-11-08 00:00:00.000. While reading from db in C#, it's read as local time and not UTC. ex: after reading the dateTime value, a dateTime.ToUniversalTime() gives a different value.

How do I read the db datetime value as UTC and not local time? Or I should saved in local time in t-sql?

like image 238
hIpPy Avatar asked Nov 11 '11 16:11

hIpPy


People also ask

How do I get the UTC DateTime in SQL Server?

SQL Server GETUTCDATE() Function The GETUTCDATE() function returns the current database system UTC date and time, in a 'YYYY-MM-DD hh:mm:ss. mmm' format.

How do I convert UTC time to local time in SQL?

SELECT CONVERT(datetime, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, GETUTCDATE()), DATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) AS LOCAL_IST; Here, the GETUTCDATE() function can be used to get the current date and time UTC. Using this query the UTC gets converted to local IST.

Is SQL DateTime UTC?

Regarding serialization and moving data between computers, there is no need to bother, as the datetime is always UTC.

Does SQL DateTime store timezone?

To provide an answer, in short Neither Datetime nor Datetime2 encodes timezone information, only the raw date/time data specified.


1 Answers

Okay, if you're getting a DateTime with a Kind of Unspecified, you can just use:

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

This sort of problem is just one of the reasons I dislike DateTime.

like image 170
Jon Skeet Avatar answered Oct 05 '22 16:10

Jon Skeet