Is there any CURRENT_TIMEZONE_ID equivalent function in SQL Server?
There is an ugly way to read the current timezone id in SQL Server by reading the registry key like this
but I cannot read registry in my server due to security constraints and personally also I do not like the solution.
And I could not find any direct way or function similar to this CURRENT_TIMEZONE_ID for SQL Server.
Is there any?
2条答案
按热度按时间huwehgph1#
Have a look at
This gives the timezone offset of the server in relation to UTC.
Small side note, perhaps make it a thing to store all dates as UTC, this way you in SQL and well as the developers can deal with the date and convert it to local dates easily as there is no guessing was the data entered by a server on a server standing in Asia or in the US. The default for server time is GetDate(), the same for UTC is GetUtcDate(), not too hard to do...
You can read the time zone from the registry (you will need permission that opens lots of security issues and is usually not given) like this:
Update based on your answer
As mentioned above., you can use Sysdatetimeoffset(), Unless you know that LAT/ LONG or are able to use .Net and created extended property the only TSQL way to get approximately value by getting the offset and map that with the time zone names in SQL server.
Here are 2 samples, the first takes the timezone offset and places it in a variable, then query the table with the offset variable
or use a subquery, basically two ways to do the same same thing
If you do not want to read the registry and you need to be precise then use CLR user-defined function and deploy that to your database
You could do this with relatively few lines of code:
A good sample for creating, deploying etc is here https://sqlclr-tutorial.net/en/tutorial/100006/clr-user-defined-functions
As you access no objects in SQL and perform or external access all SQL instances could allow this as it's safe code
nc1teljy2#
Based on info here: https://learn.microsoft.com/en-us/azure/azure-sql/managed-instance/timezones-overview
Then get it like:
Can now create things like:
To get local datetime in utc: