K M K M - 1 year ago 141
SQL Question

How to SELECT the UTC offset from a DateTimeOffset object?

I am currently using:


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

Thank you.

Answer Source

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:


For more information about CAST and CONVERT see here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download