问题
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