In SQL Server, the transact-sql SYSDATETIMEOFFSET()
function returns a datetimeoffset(7) value that contains the date and time of the computer on which the instance of SQL Server is running. This value includes the time zone offset.
Examples of usage below.
Syntax
The syntax goes like this:
SYSDATETIMEOFFSET ( )
So you simply call the function without any arguments.
Example
Here’s a basic example:
SELECT SYSDATETIMEOFFSET() AS Result;
Result:
Result ---------------------------------- 2018-06-17 09:55:27.3221853 +10:00
Extracting the Time Zone Offset
You can use the DATEPART()
function to return the time zone offset. This function returns an integer that represents the time zone offset in minutes.
Example:
SELECT SYSDATETIMEOFFSET() AS 'Date/time', DATEPART(TZoffset, SYSDATETIMEOFFSET()) AS 'TZ Offset';
Result:
Date/time TZ Offset ---------------------------------- ----------- 2018-06-17 10:04:23.2316409 +10:00 600
You can also use the FORMAT() function to return the time zone offset as a string. Specifically, you can use the z
, zz
, and/or zzz
arguments to return it in the required format.
Example:
SELECT SYSDATETIMEOFFSET() AS 'Date/time', FORMAT(SYSDATETIMEOFFSET(), 'zz') AS 'zz', FORMAT(SYSDATETIMEOFFSET(), 'zzz') AS 'zzz';
Result:
Date/time zz zzz ---------------------------------- -------------- -------------- 2018-06-17 10:27:33.7314840 +10:00 +10 +10:00
Converting the Return Value
You can also use functions such as CONVERT()
to convert the return value into another data type. Here’s an example where I convert it into a date value and a time value:
SELECT CONVERT (date, SYSDATETIMEOFFSET()) AS 'Date', CONVERT (time, SYSDATETIMEOFFSET()) AS 'Time';
Result:
Date Time ---------- ---------------- 2018-06-17 10:08:29.6377947
Of course, once we do that, we lose the time zone offset.
Also see TODATETIMEOFFSET()
which allows you to get a datetimeoffset value from a datetime2 expression, and SWITCHOFFSET()
which allows you to change a time zone offset.