SDU Tools: Converting to/from Unix time in SQL Server T-SQL

I do a lot of data conversion work each month. Many systems store date and time values in Unix format, so I often need to convert to/from these in T-SQL. Fortunately it’s easy.
A common way that Unix systems store the date and time value, is to store the number of seconds since the beginning of 1970.
The DateTime2ToUnixTime and UnixTimeToDateTime2 functions in our free SDU Tools for developers and DBAs, does this.
They each take one parameter, which is the value to convert.
Find out more
You can see them in action in the main image above, and in the video here. The full current version of the code is also shown below:
You can use our tools as a set or as a great example of how to write functions like these.
Access to SDU Tools is one of the benefits of being an SDU Insider, along with access to our other free tools and eBooks. Please just visit here for more info:
http://sdutools.sqldownunder.com
Latest version of the code
Note: the code might wrap when displayed below.
CREATE OR ALTER FUNCTION SDU_Tools.DateTime2ToUnixTime
(
@ValueToConvert datetime2(0)
)
RETURNS bigint
AS
BEGIN
-- Function: Converts a datetime2 value to Unix time
-- Parameters: @ValueToConvert datetime2(0) -> the value to convert
-- Action: Converts a datetime2 value to Unix time
-- Return: bigint
-- Refer to this video: https://youtu.be/tGplVv-G3E4
--
-- Test examples:
/*
SELECT SDU_Tools.DateTime2ToUnixTime('20450101');
*/
RETURN DATEDIFF_BIG(second, '19700101', @ValueToConvert);
END;
GO
------------------------------------------------------------------------------------
CREATE OR ALTER FUNCTION SDU_Tools.UnixTimeToDateTime2
(
@ValueToConvert bigint
)
RETURNS datetime2(0)
AS
BEGIN
-- Function: Converts a Unix time to a datetime2 value
-- Parameters: @ValueToConvert bigint -> the value to convert
-- Action: Converts a Unix time to a datetime2 value
-- Return: datetime2(0)
-- Refer to this video: https://youtu.be/tGplVv-G3E4
--
-- Test examples:
/*
SELECT SDU_Tools.UnixTimeToDateTime2(2366841600);
*/
RETURN DATEADD(day, @ValueToConvert / 86400, DATEADD(second, @ValueToConvert % 86400, '19700101'));
END;
GO
2021-01-15