How to convert local time to UTC time in SQL
Please help to find how we can convert Local time to UTC time in SQL..?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Hemant SrivastavaPosted Feb 5, 2013, 10:27 AM
For your First question,
if you change hour to minute or second or any date part, SQL sever puts your Local Time-UTC Difference in that unit. It means, suppose difference is 5 hours between your local time and UTC time and you use 'Seconds'segment here instead of 'Hour', SQL server converts that time difference into seconds (i.e 18000 seconds). Even if you use 'DATE' part, SQL server will give the same UTC time.
For your second question, it takes care your date, month year change it's because you are using Built-in SQL method 'DATEADD()' that is supposed to handle all of these date change issues.
DECLARE @DIFF INT
SET @DIFF = DATEDIFF(HOUR,GETDATE(),GETUTCDATE())
SELECT @DIFF AS DIFFERENCE_IN_HOUR
SELECT DATEADD(HOUR, @DIFF, GETDATE()) AS CURRENT_UTC_TIME
------------------------------------------------------------
DECLARE @DIFF1 INT
SET @DIFF1 = DATEDIFF(MINUTE,GETDATE(),GETUTCDATE())
SELECT @DIFF1 AS DIFFERENCE_IN_MINUTE
SELECT DATEADD(MINUTE, @DIFF1, GETDATE()) AS CURRENT_UTC_TIME
-------------------------------------------------------------
DECLARE @DIFF2 INT
SET @DIFF2 = DATEDIFF(SECOND,GETDATE(),GETUTCDATE())
SELECT @DIFF2 AS DIFFERENCE_IN_SECONDS
SELECT DATEADD(SECOND, @DIFF2, GETDATE()) AS CURRENT_UTC_TIME
------------------------------------------------------------
DECLARE @DIFF3 INT
SET @DIFF3 = DATEDIFF(DAY,GETDATE(),GETUTCDATE())
SELECT @DIFF3 AS DIFFERENCE_IN_DAYS
SELECT DATEADD(DAY, @DIFF3, GETDATE()) AS CURRENT_UTC_TIME
-----------------------------------------------------------
you may look the sql query result:
Ann AsejoPosted Feb 6, 2015, 3:59 AM
Hemant SrivastavaPosted Feb 5, 2013, 6:02 PM
Tulika KumarPosted Feb 5, 2013, 1:39 PM
Tulika KumarPosted Feb 5, 2013, 9:54 AM
Thanks Hemant, you solution is working fine but I have doubts... like:
1. Why are you considering only HOUR part.. what about other minutes and seconds?
2. At that time, when date is changed after UTC conversion, will it work?
Jignesh TrivediPosted Feb 4, 2013, 10:32 PM
check below link
it might help inyou problem
http://stackoverflow.com/questions/6064674/sql-server-2008-how-to-convert-gmtutc-datetime-to-local-datetime
DeepeshPosted Feb 4, 2013, 7:13 PM
First create the function attached in the file. Parameters are local time and your timezone.
Then call it like below:
DECLARE @DT DATETIME = GETDATE()
SELECT @DT AS LOCAL_TIME, dbo.GET_UTCTIME(@DT, 'CT') AS UTC_TIME
Hope this helps and solves your problem.
Hemant SrivastavaPosted Feb 4, 2013, 6:59 PM
DECLARE @DIFF INT
SET @DIFF = DATEDIFF(HOUR,GETDATE(),GETUTCDATE())
SELECT DATEADD(HH, @DIFF, GETDATE())