How to SELECT the UTC offset from a DateTimeOffset object?

时光怂恿深爱的人放手 提交于 2019-12-10 22:09:08

问题


I am currently using:

SELECT DATEPART(TZ, SYSDATETIMEOFFSET())

However, it returns the offset in minutes. I would like to preserve the format of '-05:00' instead of '-300'

Thank you.


回答1:


If you want to extract the exact string '-05:00' at the end of a datetimeoffset variable, you can use SQL Server string manipulation. I do not think it is possible to do this using the built-in SQL DateTime functions. You can use the CAST function, which I believe defaults to ISO 8601 format:

declare @timeStr nvarchar(50) = CAST(SYSDATETIMEOFFSET() as nvarchar(50))
select right(@timeStr, 6)

If you want to be more explicit, you can use the CONVERT function with a format type of 126, explicitly telling SQL Server to use ISO 8601:

declare @timeStr nvarchar(50) = CONVERT(nvarchar(50), SYSDATETIMEOFFSET(), 126)
select right(@timeStr, 6)

Both of these approaches in my time zone return:

-06:00

For more information about CAST and CONVERT see here.




回答2:


In MS SQL Server you can also use

SELECT DATENAME(tz, SYSDATETIMEOFFSET())

which will return a nvarchar with the offset

screenshot of the excecution result



来源:https://stackoverflow.com/questions/14060535/how-to-select-the-utc-offset-from-a-datetimeoffset-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!