SQL Server : DATEDIFF not accurate - sql-server

I'm trying to retrieve the month difference of two dates but it seems like I can't find a way to get the accurate months.
Here are the queries I tried so far :
SELECT DATEDIFF(month,convert(datetime, '11/05/2015'), convert(datetime, '12/06/2015')) - 1
This will result to 0 which is wrong and when I used another date :
SELECT DATEDIFF(month,convert(datetime, '12/31/2015'), convert(datetime, '01/01/2016')) - 1
This would yield to 0 which is correct.
Leap year must also be considered.

The TSQL is return the correct results as you have written them. As you have it, it is taking the difference of the months between the two dates specified.
SELECT DATEDIFF(month, convert(datetime, '11/05/2015'), convert(datetime, '12/06/2015'))
The difference, in months, between November and December is "1".
However, if you are wanting the difference in terms of every 30 days is 1 month, then you would need to rewrite your query:
declare #daysPerMonth int = 30
SELECT (DATEDIFF(day, convert(datetime, '11/05/2015'), convert(datetime, '12/06/2015')) / #daysPerMonth)
This works if you define the number of days in a month as 30.

Here is a way to visualize what DATEDIFF(month, ...) is doing. Think of a monthly calendar hanging on the wall. For the purposes of this particular SQL function "number" of months between two dates is the number of pages you have to flip to get from one date to the next. It doesn't matter how many days are in each month or whether it's a leap year.
You aren't the first person to be confused about the behavior of the built-in function. If you need to count months by a different method then you'll need to describe the specifics of what you want to accomplish. It's very likely that a solution will be easy to create once you define the problem that needs to be addressed.

In T-SQL you can use CASE:
SELECT DATEDIFF(month, convert(datetime, '11/05/2015'),
convert(datetime, '12/06/2015')) -
CASE
WHEN (MONTH('11/05/2015') > MONTH('12/06/2015')
OR MONTH('11/05/2015') = MONTH('12/06/2015')
AND DAY('11/05/2015') > DAY('12/06/2015'))
THEN 1 ELSE 0
END
Which returns 1 which is correct and:
SELECT DATEDIFF(month, convert(datetime, '12/31/2015'),
convert(datetime, '01/01/2016')) -
CASE
WHEN (MONTH('12/31/2015') > MONTH('01/01/2016')
OR MONTH('12/31/2015') = MONTH('01/01/2016')
AND DAY('12/31/2015') > DAY('01/01/2016'))
THEN 1 ELSE 0
END
Which returns 0 which is correct.

declare
#start date = '20220105',
#end date = '20220406'
select 'Date_Diff_In_3 months' =
case
when datediff(month, #start, #end) < 3
or (datediff(month, #start, #end) = 3 and day(#start) >= day(#end))
then 'yes'
else 'no'
end

Related

Finding Months Difference in Days

I want to find the difference between two dates which should be exact in months like if the date difference is greater than 182 days them on 183rd Day it should show as 7 Months.I tried below one,
SELECT ROUND(cast(DATEDIFF(DD,'2018-01-01 18:45:30.203',GETDATE()) as float)/30,0)
but it has 15 days difference.
I wouldn’t use 30. It’s fail on some months. For example Jan 1 and March 2 since February doesn’t have at least 30 days. But I think this is what you are after. If the current day isn’t the first of the month then add a month.
SELECT
Case
when datepart(day,getdate()) > 1
Then datediff(month,'2018-01-01 18:45:30.203',GETDATE()) + 1
Else datediff(month,'2018-01-01 18:45:30.203',GETDATE())
End
I think that calculating the difference in months as an integer is very similar to calculating the age of a person. We can take the DATEDIFF in months, add this number of months to the first date and compare that to the second date to decide whether we have to subtract 1 from the difference:
DECLARE #Date1 datetime = '2018-01-01 18:45:30.203';
DECLARE #Date2 datetime = GETDATE();
SELECT
CASE
WHEN DATEADD(month, DATEDIFF(month, #Date1, #Date2), #Date1) > #Date2
THEN DATEDIFF(month, #Date1, #Date2) - 1
ELSE DATEDIFF(month, #Date1, #Date2)
END

Counting datediff from 2 date

I have 2 datetime fields, NEW_EMPLOYMENT_STARTDATE and NEW_EMPLOYMENT_ENDDATE
When I calculate the difference in months using datediff with these values for startdate and enddate:
NEW_EMPLOYMENT_STARTDATE = 2017-15-01
NEW_EMPLOYMENT_ENDDATE = 2018-14-01
With this query:
DATEDIFF(MONTH, NEW_EMPLOYMENT_STARTDATE, NEW_EMPLOYMENT_ENDDATE)
It returns 12 months, but when I have values like this:
NEW_EMPLOYMENT_STARTDATE = 2017-01-01
NEW_EMPLOYMENT_ENDDATE = 2017-31-12
It returns 11 months.
How can I get 12 months? I am using this query:
DATEDIFF(MONTH, NEW_EMPLOYMENT_STARTDATE, NEW_EMPLOYMENT_ENDDATE)-
CASE
WHEN DATEPART(DAY, NEW_EMPLOYMENT_ENDDATE) > DATEPART(DAY, NEW_EMPLOYMENT_STARTDATE)
THEN 0
ELSE 0 END AS MONTH_DIFF
It still returns 11 months.
EDIT:
According to my case, the value of the end date always less 1 day from start date, so i make a trick to check condition with case when like this:
CASE
WHEN DATEPART(DAY, NEW_EMPLOYMENT_ENDDATE) > DATEPART(DAY, NEW_EMPLOYMENT_STARTDATE)
THEN DATEDIFF(MONTH, NEW_EMPLOYMENT_STARTDATE, NEW_EMPLOYMENT_ENDDATE)+1
ELSE DATEDIFF(MONTH, NEW_EMPLOYMENT_STARTDATE, NEW_EMPLOYMENT_ENDDATE)
END AS DATEDIF
i add + 1 value to the end date so i ta can be round to next month, give feedback from my solution sir thanks
You're expectations are incorrect. When you do a DATEDIFF using MONTH, it does not consider the day portion of the dates. Consider that it is simply considering the difference in the month numbers only, regardless of the day specified.
This query:
SELECT DATEDIFF(MONTH, '20170101', '20171231') MonthsDiff
Is equivalent to this:
SELECT DATEPART(MONTH, '20171231') - DATEPART(MONTH, '20170101') MonthsDiff
The documentation for DATEDIFF states:
DATEDIFF ( datepart , startdate , enddate )
The first option is DATEPART:
datepart
Is the part of startdate and enddate that specifies the type of boundary crossed.
If you want something closer to what you expect, you can do a simple calculation based on performing the DATEDIFF in days, the dividing it by the approximate number of days in a month.
SELECT DATEDIFF(DAY, '20170101', '20171231') / ( 365 / 12 ) MonthsDiff
This will round the output to the closest month number, it all depends on how accurate you want to be. If you want months as a decimal for greater accuracy then run the below:
SELECT DATEDIFF(DAY, '20170101', '20171220') / ( 365.00 / 12 ) MonthsDiff
Note: This does not take into account leap years, for larger date ranges that might include leap years, which will make a minor difference to the accuracy.
datediff() does something very particular. It counts the number of "boundaries" between two date/time values. In your case, there are eleven boundaries -- one for each month in the year before December.
This behavior is not necessarily intuitive. If you add one day to each of your dates:
NEW_EMPLOYMENT_STARTDATE = '2017-01-02' (YYYY-MM-DD is standard format)
NEW_EMPLOYMENT_ENDDATE = '2018-01-01'
Then you will have 12 months.
If you want to round up, you can play with the dates. One method would be to normalize the first value to the beginning of the month and then add 15 days to the second value:
DATEDIFF(MONTH,
DATEADD(DAY, 1 - DAY(NEW_EMPLOYMENT_STARTDATE), NEW_EMPLOYMENT_STARTDATE)
DATEADD(DAY, 15 + 1 - DAY(NEW_EMPLOYMENT_STARTDATE), NEW_EMPLOYMENT_ENDDATE)
)
This would happen to work for the two examples you give.
Please use this select to achieve your desired result. You can use table columns instead of variables:
declare #new_employment_startdate datetime = convert (datetime, '2017-01-01', 121);
declare #new_employment_enddate datetime = convert (datetime, '2018-01-14', 121);
select
datediff(month, #new_employment_startdate, #new_employment_enddate)
+ case when
datediff(month, dateadd(ms, -3, dateadd(dd, datediff(dd, 0, #new_employment_startdate), 0)), #new_employment_startdate) = 1
and datediff(month,#new_employment_enddate , dateadd(dd, datediff(dd, 0, #new_employment_enddate) + 1, 0)) = 1
then 1
else 0
end;
Some explanations:
I check or start date is first month day AND end date is last month day. At this case I add +1 to standard datediff by month.
You can better understand my used datetime manipulations by using these example queries: https://gist.github.com/runnerlt/60636b029ab47845fdfd8924ed482e61
You need to add 1 more day in your End Date.
DATEDIFF(MONTH, NEW_EMPLOYMENT_STARTDATE, DATEADD(DD,1,NEW_EMPLOYMENT_ENDDATE))
You could match the output with MS Excel.

T-SQL Count days between two days (datediff not quite working)

We have a requirement to bill our customers per day. We bill for an asset's existence in our system on that day. So, I started with datediff...
select datediff(dd ,'2015-04-24 12:59:32.050' ,'2015-05-01 00:59:59.000');
Returns this:
7
But I need to count the following dates: 4/24,4/25,4/26,4/27,4/28,4/29, 4/30, 5/1, which are 8 days. So datediff isn't quite working right. I tried these variations below
--too simple, returns 7, i need it to return 8
select datediff(dd ,'2015-04-24 12:59:32.050', '2015-05-01 23:59:59.000');
--looking better, this returns the 8 i need
select ceiling(datediff(hh,'2015-04-24 12:59:32.050', '2015-05-01 23:59:59.000')/24.0);
-- returns 7, even though the answer still needs to be 8. (changed enddate)
select ceiling(datediff(hh,'2015-04-24 12:59:32.050', '2015-05-01 00:59:59.000')/24.0);
So, my question... How, in SQL, would I derive the date count like i described, since I believe datediff counts the number of day boundaries crossed.... My current best approach is loop through each day in a cursor and count. Ick.
Use CONVERT to get rid of the time part, add 1 to get the desired result:
SELECT DATEDIFF(dd,
CONVERT(DATE, '2015-04-24 12:59:32.050'),
CONVERT(DATE, '2015-05-01 00:59:59.000')) + 1;
It turns out the time part does not play any significant role in DATEDIFF when dd is used as the datepart argument. Hence, CONVERT is redundant. This:
SELECT DATEDIFF(dd, '2015-04-24 23:59:59.59','2015-05-01 00:00:00.000') + 1
will return 8 as well.
You could try this which would return 8 days.
select datediff(dd ,'2015-04-24 12:59:32.050' ,CASE DATEDIFF(Second,'2015-05-01 00:00:00.000','2015-05-01 23:59:59.000') WHEN 0 THEN '2015-05-01 23:59:59.000' ELSE DATEADD(dd,+1,'2015-05-01 23:59:59.000') END)
If you want to use variables for your dates then something like this would work.
BEGIN
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
DECLARE #EndDateOnly DATE
SET #StartDate = '2015-04-24 12:59:32.050'
SET #EndDate = '2015-05-01 23:59:59.000'
SET #EndDateOnly = CAST(#EndDate AS DATE)
SELECT datediff(dd ,#StartDate ,CASE DATEDIFF(Second,CAST(#EndDateOnly||' 00:00:00.000' AS DATETIME),#EndDate) WHEN 0 THEN #EndDate ELSE DATEADD(dd,+1,#EndDate) END)
END

SQL - Find working hours between 2 dates excluding weekends

I'm working on a code to get net working days excluding weekends (saturday and sunday). I need this data in days. I've written following 2 functions for it
The first function returns the start time of the date
ALTER FUNCTION day_start
(#dd as datetime)
returns datetime
begin
return cast(floor(cast(#dd as float)) as datetime)
end
The second one does the actual work
alter function networkingdays_hours (#startdate as datetime, #enddate as datetime)
returns float
begin
return
(
SELECT
cast(
(DATEDIFF(dd,#StartDate, #EndDate))
-(DATEDIFF(wk,#StartDate, #EndDate)*2)
-(CASE WHEN DATENAME(dw, #StartDate) ='Sunday'
THEN 1
ELSE 0
END)
-(CASE WHEN DATENAME(dw, #EndDate) ='Saturday'
THEN 1
ELSE 0
END)
+(#EndDate - dbo.day_start(#EndDate))
-(#startdate - dbo.day_start(#startdate))
as float))
END
Example
start time - 8/31/2012 9:22:00 AM, End Time - 9/1/2012 7:14:00 AM, Expected result - 0.911111111, Code output - (-0.08888888)
Please help.
Your function doesn't work in this specific case because Sept 1 is a weekend, and you have indicated that 1 should be subtracted from the result if that is the case.
In the general case, it doesn't work, because there will be an increasing number of special and edge cases that require ever more convoluted logic.
Creating a working days table is a much more flexible solution

SQL Server - Finding the first day of the week

I've been looking around for a chunk of code to find the first day of the current week, and everywhere I look I see this:
DATEADD(WK, DATEDIFF(WK,0,GETDATE()),0)
Every place says this is the code I'm looking for.
The problem with this piece of code is that if you run it for Sunday it chooses the following Monday.
If I run:
SELECT GetDate() , DATEADD(WK, DATEDIFF(WK,0,GETDATE()),0)
Results for today (Tuesday):
2013-05-14 09:36:39.650................2013-05-13 00:00:00.000
This is correct, it chooses Monday the 13th.
If I run:
SELECT GetDate()-1 , DATEADD(WK, DATEDIFF(WK,0,GETDATE()-1),0)
Results for yesterday (Monday):
2013-05-13 09:38:57.950................2013-05-13 00:00:00.000
This is correct, it chooses Monday the 13th.
If I run:
SELECT GetDate()-2 , DATEADD(WK, DATEDIFF(WK,0,GETDATE()-2),0)
Results for the 12th (Sunday):
2013-05-12 09:40:14.817................2013-05-13 00:00:00.000
This is NOT correct, it chooses Monday the 13th when it should choose the previous Monday, the 6th.
Can anyone illuminate me as to what's going in here? I find it hard to believe that no one has pointed out that this doesn't work, so I'm wondering what I'm missing.
It is DATEDIFF that returns the "incorrect" difference of weeks, which in the end results in the wrong Monday. And that is because DATEDIFF(WEEK, ...) doesn't respect the DATEFIRST setting, which I'm assuming you have set to 1 (Monday), and instead always considers the week crossing to be from Saturday to Sunday, or, in other words, it unconditionally considers Sunday to be the first day of the week in this context.
As for an explanation for that, so far I haven't been able to find an official one, but I believe this must have something to do with the DATEDIFF function being one of those SQL Server treats as always deterministic. Apparently, if DATEDIFF(WEEK, ...) relied on the DATEFIRST, it could no longer be considered always deterministic, which I can only guess wasn't how the developers of SQL Server wanted it.
To find the first day of the week's date, I would (and most often do actually) use the first suggestion in #Jasmina Shevchenko's answer:
DATEADD(DAY, 1 - DATEPART(WEEKDAY, #Date), #Date)
DATEPART does respect the DATEFIRST setting and (most likely as a result) it is absent from the list of always deterministic functions.
Try this one -
SET DATEFIRST 1
DECLARE #Date DATETIME
SELECT #Date = GETDATE()
SELECT CAST(DATEADD(DAY, 1 - DATEPART(WEEKDAY, #Date), #Date) AS DATE)
SELECT CAST(#Date - 2 AS DATE), CAST(DATEADD(WK, DATEDIFF(WK, 0, #Date-2), 0) AS DATE)
Results:
---------- ----------
2013-05-12 2013-05-13
SQL Server has a SET DATEFIRST function which allows you to tell it what the first day of the week should be. SET DATEFIRST = 1 tells it to consider Monday as the first day of the week. You should check what the server's default setting is via ##DATEFIRST. Or you could simply change it at the start of your query.
Some references:
MSDN
Similar Question
That worked for me like a charm:
Setting moday as first day of the week without changing DATEFIRST variable:
-- FirstDayWeek
select dateadd(dd,(datepart(dw, case datepart(dw, [yourDate]) when 1 then dateadd(dd,-1,[yourDate]) else [yourDate] end) * -1) + 2, case datepart(dw, [yourDate]) when 1 then dateadd(dd,-1,[yourDate]) else [yourDate] end) as FirstDayWeek;
-- LastDayWeek
select dateadd(dd, (case datepart(dw, [yourDate]) when 1 then datepart(dw, dateadd(dd,-1,[yourDate])) else datepart(dw, [yourDate]) end * -1) + 8, case datepart(dw, [yourDate]) when 1 then dateadd(dd,-1,[yourDate]) else [yourDate] end) as LastDayWeek;
Setting sunday as fist day of the week without changing DATEFIRST variable
select convert(varchar(50), dateadd(dd, (datepart(dw, [yourDate]) * -1) + 2, [yourDate]), 103) as FirstDayWeek, convert(varchar(50), dateadd(dd, (datepart(dw, [yourDate]) * -1) + 8, [yourDate]), 103) as LastDayWeek;
You can change [yourDate] by GETDATE() for testing

Resources