To be consistent with what is probably the most likely source of generating a time span (computing the difference of 2 times or date-times), you may want to store a .NET TimeSpan
as a SQL Server DateTime
Type.
This is because in SQL Server, the difference of 2 DateTime
's (Cast
to Float
's and then Cast
back to a DateTime
) is simply a DateTime
relative to Jan. 1, 1900. Ex. A difference of +0.1 second would be January 1, 1900 00:00:00.100 and -0.1 second would be Dec. 31, 1899 23:59:59.900.
To convert a .NET TimeSpan
to a SQL Server DateTime
Type, you would first convert it to a .NET DateTime
Type by adding it to a DateTime
of Jan. 1, 1900. Of course, when you read it into .NET from SQL Server, you would first read it into a .NET DateTime
and then subtract Jan. 1, 1900 from it to convert it to a .NET TimeSpan
.
For use cases where the time spans are being generated from SQL Server DateTime
's and within SQL Server (i.e. via T-SQL) and SQL Server is prior to 2016, depending on your range and precision needs, it may not be practical to store them as milliseconds (not to mention Ticks
) because the Int
Type returned by DateDiff
(vs. the BigInt
from SS 2016+'s DateDiff_Big
) overflows after ~24 days worth of milliseconds and ~67 yrs. of seconds. Whereas, this solution will handle time spans with precision down to 0.1 seconds and from -147 to +8,099 yrs..
WARNINGS:
This would only work if the difference relative to Jan. 1, 1900 would result in a value within the range of a SQL Server DateTime
Type (Jan. 1, 1753 to Dec. 31, 9999 aka -147 to +8,099 yrs.). We don't have to worry near as much on the .NET TimeSpan
side, since it can hold ~29 k to +29 k yrs. I didn't mention the SQL Server DateTime2
Type (whose range, on the negative side, is much greater than SQL Server DateTime
's), because: a) it cannot be converted to a numeric via a simple Cast
and b) DateTime
's range should suffice for the vast majority of use cases.
SQL Server DateTime
differences computed via the Cast
- to - Float
- and - back method does not appear to be accurate beyond 0.1 seconds.