Reputation: 93
We have multi columns in sql in local time zones like EST ,PST , CST and so on . We would like convert all these time zones in UTC time zones considering Day light savings into account and save it to another column.
I tried below query but it converts UTC to local time zone (EST) but I am looking for EST to UTC time zone.
select CONVERT(datetime, SWITCHOFFSET(dateTimeField, DATEPART(TZOFFSET, dateTimeField AT TIME ZONE 'Eastern Standard Time')))
Upvotes: 1
Views: 3420
Reputation: 32717
Based on a comment above, you should be able to use the following example to get what you want.
DECLARE @ts DATETIME = GETDATE();
SELECT
@ts AT TIME ZONE 'Pacific Standard Time',
@ts AT TIME ZONE 'Pacific Standard Time' AT TIME ZONE 'UTC',
CAST(@ts AT TIME ZONE 'Pacific Standard Time' AT TIME ZONE 'UTC' AS DATETIME)
What I'm showing here is the various steps. In turn:
datetime
value. This could easily be a column from your table.To be explicit about "what would this look like if I wanted to convert the data in my table?", it'd look something like this:
alter table dbo.yourTable add
isConverted bit
constraint DF_yourTable_isConverted default 0;
update top(1000) dbo.yourTable
set yourColumn = CAST(
yourColumn AT TIME ZONE 'Pacific Standard Time' AT TIME ZONE 'UTC'
AS DATETIME
),
isConverted = 1
where isConverted = 0;
Note I've added a column whose purpose is to provide a notion of "has this particular row's column been converted?" so you don't accidentally convert a given value twice. Once all the data in the table is converted, you can drop the column.
Upvotes: 3