I'm doing a few SQL select queries and would like to convert my UTC datetime column into local time to be displayed as local time in my query results. Note, I am NOT looking to do this conversion via code but rather when I am doing manual and random SQL queries against my databases.
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- What is the best way to cache a table from a (SQL)
- php PDO::FETCH_ASSOC doesnt detect select after ba
There is no simple way to do this in a correct AND generic way.
First of all it must be understood that the offset depends on the date in question, the Time Zone AND DST.
GetDate()-GetUTCDate
only gives you the offset today at the server's TZ, which is not relevant.I have seen only two working solution and I have search a lot.
1) A custom SQL function with a a couple of tables of base data such as Time Zones and DST rules per TZ. Working but not very elegant. I can't post it since I don't own the code.
EDIT: Here is an example of this method https://gist.github.com/drumsta/16b79cee6bc195cd89c8
2) Add a .net assembly to the db, .Net can do this very easily. This is working very well but the downside is that you need to configure several parameters on server level and the config is easily broken e.g. if you restore the database. I use this method but I cant post it since I don't own the code.
It's simple. Try this for Azure SQL Server:
For Local SQL Server :
SELECT CONVERT(datetime2, SWITCHOFFSET(CONVERT(datetimeoffset, gETDATE()), DATENAME(TzOffset, gETDATE() AT TIME ZONE 'Eastern Standard Time'))) FROM YourTable
Ron's answer contains an error. It uses 2:00 AM local time where the UTC equivalent is required. I don't have enough reputation points to comment on Ron's answer so a corrected version appears below:
None of these worked for me but this below worked 100%. Hope this can help others trying to convert it like I was.
First function: configured for italian time zone (+1, +2), switch dates: last sunday of march and october, return the difference between the current time zone and the datetime as parameter.
The code is:
Then the function that convert date
You can do this as follows on SQL Server 2008 or greater:
You can also do the less verbose:
Whatever you do, do not use
-
to subtract dates, because the operation is not atomic, and you will on occasion get indeterminate results due to race conditions between the system datetime and the local datetime being checked at different times (i.e., non-atomically).Please note that this answer does not take DST into account. If you want to include a DST adjustment, please also see the following SO question:
How to create Daylight Savings time Start and End function in SQL Server