Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

sql server - Convert datetime value from one timezone to UTC timezone using sql query

I have a datetime value. That datetime value may be in any timezone like 'Eastern Standard Time' or 'India Standard Time'. I want to convert that datetime value to UTC timezone in SQL. Here from timezone value will be the given parameter. I can achieve this using C# code also. But I need this in SQL query.

Can anyone tell me how can I convert that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Timezone and timezone offset are two different things. A timezone can have different offsets if daylight savings time is used. Timezone support was added to SQL Server in the latest version, 2016.

Your question has two parts - how to convert a datetime value to a value with offset/timezone and then how to convert that value to a UTC.

In versions up to SQL Server 2014, you have to determine the correct offset for your local timezone in advance, eg using C# code. Once you have it you can convert a datetime to a `datetimeoffset with a specific offset with TODATETIMEOFFSET:

select TODATETIMEOFFSET(GETDATE(),'02:00')

or

select TODATETIMEOFFSET(GETDATE(),120)

This will return a datetimeoffset value with the original time and the specified offset.

Switch to another offset (eg UTC) is performed by the SWITCHOFFSET function

select SWITCHOFFSET(@someDateTimeOffset,0)

You can combine both with

select SWITCHOFFSET(TODATETIMEOFFSET(GETDATE(),120),0)

The offset can be passed as a parameter. Assuming your field is called SomeTime, you could write

select SWITCHOFFSET(TODATETIMEOFFSET(SomeTime,@offsetInMinutes),0)

In SQL Server 2016 you can use the timezone names. You still need a double conversion though, first to the local timezone then to UTC:

SELECT (getdate() at time zone 'Central Europe Standard Time') AT TIME ZONE 'UTC'

The first AT TIMEZONE returns a datetimeoffset with a +2:00 offset and the second converts it to UTC.

NOTE

You could probably avoid all conversions if you used the datetimeinfo type instead of datetime. SQL Server allows comparisons, filtering, calculations etc on values of different offsets, so you wouldn't need to make any conversions for querying. On the client side, .NET has the equivalent DateTimeOffset type so you wouldn't need to make any conversion in client code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...