emi_sastra
asked on
Datediff get wrong months calculations.
Hi There,
I have two date. 2018-11-01 2020-04-30
I use datediff and I get 17 months ? It should 18 months :
1. 2018 = 2 months
2. 2019 = 12 months
3. 2020 = 4 months
Why?
Thank you
I have two date. 2018-11-01 2020-04-30
I use datediff and I get 17 months ? It should 18 months :
1. 2018 = 2 months
2. 2019 = 12 months
3. 2020 = 4 months
Why?
Thank you
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
DATEDIFF does not calculate full months it just subtract the months between 2 dates.
In the following example there are only 2 hours between 2 dates but DATEDIFF shows even 1 month difference:
In the following example there are only 2 hours between 2 dates but DATEDIFF shows even 1 month difference:
select datediff(month, '2018-11-30 23:00:00', '2018-12-01 01:00:00') [months],
datediff(hour, '2018-11-30 23:00:00', '2018-12-01 01:00:00') [hours]
So in reality between '2018/11/01' and '2020/04/30' there are only 17 months difference.
ASKER
Hi All,
Which method should I use to get the nearest to manual calculation, disregards the time.?
Thank you.
Which method should I use to get the nearest to manual calculation, disregards the time.?
Thank you.
You can use:
datediff(month, '2018-11-30 23:00:00', '2018-12-01 01:00:00') + 1
ordatediff(day, '2018-11-30 23:00:00', '2018-12-01 01:00:00') / 30
none of them accurate because months have not the same number of days (furthermore years have not the same number of days).
ASKER
Hi All,
Thank you very much for your help.
Thank you very much for your help.
ASKER
Thank you all.
Hi,
Technically datediff counts edges. For instance, the following ALL (apart from weeks - thrown in for completeness to confuse myself) return 1, because there is 1 edge between the two datetimes.
HTH
David
Technically datediff counts edges. For instance, the following ALL (apart from weeks - thrown in for completeness to confuse myself) return 1, because there is 1 edge between the two datetimes.
HTH
David
use tempdb
go
declare @StartDateTime as DateTime
declare @EndDateTime as DateTime
set @StartDateTime = '2007-12-31 23:59:59'
set @EndDateTime = '2008-01-01 00:00:00'
set nocount on
select @StartDateTime, @EndDateTime
select datediff( year, @StartDateTime, @EndDateTime ) as Years
select datediff( quarter, @StartDateTime, @EndDateTime ) as Quarters
select datediff( month, @StartDateTime, @EndDateTime ) as Months
select datediff( week, @StartDateTime, @EndDateTime ) as Weeks
select datediff( day, @StartDateTime, @EndDateTime ) as Days
select datediff( hour, @StartDateTime, @EndDateTime ) as Hours
select datediff( minute, @StartDateTime, @EndDateTime ) as Minutes
select datediff( second, @StartDateTime, @EndDateTime ) as Seconds
SELECT DATEDIFF(month, '2018/11/01', '2020/05/01') AS DateDiff;
Gives 18 months.