How to Convert Local (Est ) Column Timezone to Utc Time Zone in Sql Server

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')))

10

1 Answer

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:

  1. Getting an arbitrary datetime value. This could easily be a column from your table.
  2. Telling SQL "this datetime is in the PST time zone"
  3. Telling SQL "convert this PST time to a UTC time"
  4. Casting the resulting UTC time back to a datetime (presumably so it will be able to be inserted back into the 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 double convert a given value twice. Once all the data in the table is converted, you can drop the column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest