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?
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.
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.
Regarding serialization and moving data between computers, there is no need to bother, as the datetime is always UTC.
To provide an answer, in short Neither Datetime nor Datetime2 encodes timezone information, only the raw date/time data specified.
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
.
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