How to translate T-SQL Datetime2 to Float or Real
The new Datetime2 data type introduced in Microsoft SQL Server 2008 has several advantages over the old Datetime type. One of them is precision in 100 nanoseconds rather than coarse milliseconds, another is that is has a larger date range. It has disadvantages, too, like a difficulty in translating it into numerical values.
There was a classic hack to CONVERT/CAST a Datetime into a Float in order to get a numerical value that you could manipulate (like convert it to an integer to get the date without time, which is now accomplished by converting it to Date, another type introduced in SQL Server 2008), but it won't work directly for a Datetime2 value.
As there are many reasons why one needs to translate a datetime into a numerical value, but I don't get into that, here is how to convert a Datetime2 value into a Float.
First solution:
DECLARE @Time DATETIME2 = SYSDATETIME()
SELECT DATEDIFF(SECOND,{d '1970-01-01'}, @Time)
+DATEPART(NANOSECOND,@Time)/1.0E+9
- returns a value in seconds with nanosecond precision from the beginning of the year 1970.
- Advantage: simple to use and understand.
- Disadvantage: not similar to the conversion from Datetime to Float.
Second solution:
DECLARE @Time DATETIME2 = SYSDATETIME()
SELECT DATEDIFF(DAY, {d '1900-01-01'}, @Time)
+DATEPART(HOUR,@Time)/24.0
+DATEPART(MINUTE,@Time)/(24.0*60)
+DATEPART(SECOND,@Time)/(24.0*60*60)
+DATEPART(NANOSECOND,@Time)/(24.0*60*60*1.0E+9)
- returns a value that is similar to the float conversion of a datetime.
- Advantage: doesn't lose precision like converting to a Datetime and then to Float.
- Disadvantage: look at the length of that!
Final solution:
DECLARE @Time DATETIME2 = SYSDATETIME()
SELECT (
DATEDIFF(SECOND,{d '1970-01-01'}, @Time)
+DATEPART(NANOSECOND,@Time)/1.0E+9
)/86400.0 + 25567
- combines the two solutions above.
- Advantage: It easy to read and understand.
- It computes the number of seconds with nanoseconds from 1970, divides by 86400 to get the number of days and adds 25567, which is the number of days between 1900 and 1970.
Comments
Be the first to post a comment