Click here to Skip to main content
15,903,033 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to calculate month .
select DATEDIFF(M,'31-Mar-2014','1-Jun-2014')
result is 3
but it should be 2 month bcoz 3rd month has not completed.
Posted

Hi,

Kindly go through this.

DateDiff

Hope this will clear the concepts.
 
Share this answer
 
Hi Amit,

The answer 3 is correct .

1) The start date is 31-Mar so it will count from Apr,may
and end date is 1-Jun so it will count itself including Jun also.

select DATEDIFF(M,'31-Mar-2014','1-Jun-2014')
answer :3


2) If u want the result should be 2 means
select DATEDIFF(Month,'31-Mar-2014','31-May-2014')
answer:2
 
Share this answer
 
Hi Amit,

First of all using only Datediff you won't be getting the exact month count as per your convenient.
Reason : Datediff will just return the number of Month boundaries that have been passed.

If you want month count should be returned as per exact days elapsed,try below query.

SQL
declare @startdate datetime
declare @enddate datetime
set @startdate='31-March-2014'
set @enddate='01-June-2014'



select case
        when @startdate > @enddate then NULL
        when DATEPART(day,@startdate) > DATEPART(day,@enddate) then   DATEDIFF(month,@startdate,@enddate)-1
            else DATEDIFF(month,@startdate,@enddate) end as Count_of_month


:-)
 
Share this answer
 
Comments
Sarvesh Kumar Gupta 3-Jul-14 1:00am    
It will be fail when I give Start date like as 21 March and end date like 11 june then also returns 2. This is wrong.

You have to create one UDF in sql for getting exact value. First find days then calculate the months.
Sprint89 3-Jul-14 3:29am    
"First find days then calculate the months."

There are not a standard number of days in a month, it could be 28, 29, 30 or 31. That is why you need to consider month boundaries

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900