[英]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 .我们在本地时区的 sql 中有多列,如 EST、PST、CST 等。 We would like convert all these time zones in UTC time zones considering Day light savings into account and save it to another column.
我们希望将考虑到夏令时的所有这些时区转换为 UTC 时区,并将其保存到另一列。
I tried below query but it converts UTC to local time zone (EST) but I am looking for EST to UTC time zone.我尝试了以下查询,但它将 UTC 转换为本地时区 (EST),但我正在寻找 EST 到 UTC 时区。
select CONVERT(datetime, SWITCHOFFSET(dateTimeField, DATEPART(TZOFFSET, dateTimeField AT TIME ZONE 'Eastern Standard Time')))选择 CONVERT(datetime, SWITCHOFFSET(dateTimeField, DATEPART(TZOFFSET, dateTimeField AT TIME ZONE 'Eastern Standard Time')))
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.datetime
值。 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 double convert a given value twice.
所以你不会不小心将给定的值两次转换。 Once all the data in the table is converted, you can drop the column.
转换表中的所有数据后,您可以删除该列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.