Monday, May 5, 2014

Convert local datetime to UTC or Universal data time and UTC to local datetime


--Steps required before performing conversion:

--step:

Declare @TimezoneOffset int=0

-- variable will hold the timezone difference in minutes

set @TimezoneOffset =  DATEDIFF(Minute, GETUTCDATE(), GETDATE())

--Now we have localtimezone difference with UTC.

--Convert Local datetime to UTC:-

Declare @LocalDatetime datetime= GetDate()

Declare @UTCDatetime datetime =null

select  @UTCDatetime= DateAdd(Minute,-@TimezoneOffset,@LocalDatetime)

--Convert UTC to Local datetime :-

 Declare @ConvertedLocalDatetime datetime=null

select @ConvertedLocalDatetime= DateAdd(Minute, (@TimezoneOffset),@UTCDatetime)

select 'LocalTime:-',@LocalDatetime,'  UTC Datetime : ', @UTCDatetime ,'ConvertedLocalDatetime : ', @ConvertedLocalDatetime