Wednesday, January 24, 2018

Sql Server Datetime Offset SWITCHOFFSET AT TIME ZONE

--AT TIME ZONE: time and offset are calculated for given timezone
--SWITCHOFFSET: only offset is changed, time remains the same


--create example table _dto for datetimeoffset demo
CREATE TABLE [dbo].[_dto](
[id] [int] IDENTITY(1,1) NOT NULL,
[dtoUtc] [datetimeoffset](7) NULL, --utc time
[dtoLocal] [datetimeoffset](7) NULL --local time
) ON [PRIMARY]
GO

--insert winter and sommertime demo test record
INSERT [dbo].[_dto] ( [dtoUtc]) VALUES (CAST(N'2018-01-23T10:00:00.0000000+00:00' AS DateTimeOffset)) -- winter time
GO
INSERT [dbo].[_dto] ([dtoUtc]) VALUES (CAST(N'2017-07-23T10:00:00.0000000+00:00' AS DateTimeOffset)) -- summer time
GO

--get string values for available sql server time zones:
select * from sys.time_zone_info;

--show result of SWITCHOFFSET and AT TIME ZONE
select dtoUtc ,  --original Utc Time (offset 00)
   SWITCHOFFSET(dtoUtc,1) as switch, -- time remains the same, only offset changes
   dtoUtc AT TIME ZONE 'Central Europe Standard Time' as AtTimeZone -- time and offset are transfered to destination time zone, winter and summer time are calculated correct
from _dto order by dto

--update _dto set dtoLocal= dtoUtc AT TIME ZONE 'Central Europe Standard Time' -- calculating local time from utc and store it
select * from  _dto

--drop table _dto; --clean up

1 comment:

Unknown said...

Andhra Pradesh Engineering Agricultural and Medical Common Entrance Test AP EAMCET is a state level entrance examination conducted in the state of Andhra Pradesh for the selection of candidates into Engineering and Medicine and Agriculture courses. It is conducted by Jawaharlal Nehru technical Institute.

Telangana State Engineering Agricultural and Medical Common Entrance Test TS EAMCET is a state level entrance examination conducted in the state of Telangana for the selection of candidates into Engineering and Medicine and Agriculture courses. It is conducted by Jawaharlal Nehru technical Institute (JNTU) on behalf of TSCHE.