Background Knowledge
I will explain how to convert a DATETIME (data type) value in Microsoft SQL Server to Unix timestamp and how to convert Unix timestamp to DATETIME. A Unix timestamp is a integer value of seconds since January 1, 1970 at midnight. For further explanation of Unix timestamps refer to Wikiepedia, UnixTimestamp.com or http://unixtimesta.mp/.
Note: This solution only work on dates prior to 2038-01-19 at 3:14:08 AM, where the delta in seconds exceeds the limit of the INT data type (integer is used as the result of DATEDIFF). See source for further details as I have not verified a solution to this problem.
Solutions
Convert Datetime Value to Unix Timestamp (today)
1 |
SELECT DATEDIFF(s, '19700101', GETDATE()); |
Result: 1305630800
Convert Datetime Value to Unix Timestamp from two Values
1 |
SELECT DATEDIFF(s, StartTime, EndTime) AS Duration FROM Programs |
Result: 3600
Convert Unix Timestamp Value to Datetime Value
1 |
SELECT DATEADD(s, 123456789, '19700101'); |
Result: 1973-11-29 21:33:09.000
Source: How do I convert a SQL Server DATETIME value to a
Unix timestamp?
Source: DATEADD (Transact-SQL)
Source: DATEADD
Source: DATEDIFF (Transact-SQL)
Source: DATEDIFF