I thought it was clear, but doesn’t seem so.
This question is about T-SQL (since it’s tagged with tsql 🙂 )
So I couldn’t find any out-of-the-box solution to calculate my problem.
Let’s assume you have these two dateTimes:
DECLARE @start DATETIME = '2011-01-01',
@end DATETIME = '2011-04-15'
The difference of these two datetimes in Days should be quivalent to 105.
The calculation works as follows: For every full month add 30 days, for the rest add the days till the date is achieved.
I could program this, but it would be an enormous SQL-statement, which I find find kinda ugly.
Is there any simple solution for this, like a built-in function or something short?
Thanks in advance.
Short Answer
There’s no built in function, but you could pretty easily create your own to handle converting a datetime to an int. From there, the SQL you would have to write would be trivial.
Long Answer
There’s no built in function that will do this, probably because every month doesn’t have 30 days. 🙂
You can start with this:
This isn’t beautiful SQL, but it works. Note that it returns 104 (because 15 days – 1 day = 14 days), but simple enough to tack on a
+ 1to the end of the final select if you want to handle the boundry days differently.Note that the math here could pretty easily be moved into a function, which would allow you to clean your SQL up. Let’s assume you created a function called
GetDateTimeAsIntwhich holds the math; your SQL could be as simple asIn my testing, this seems to work. It will return the same result as the
DATEDIFFfunction for the date range you specify in your post, but this is because there are 2 days with 31 days and 1 day with 28, so effectively, Jan – April have 30 days each. If you use it with a wider date range, you’ll begin to get different results with my code vs. theDATEDIFFfunction.Hope this helps.