Search Not Just Numbers

Tuesday 1 December 2015

Excel Tip: How many calendar months does a date range affect?

This week I responded to a client request for a formula that seemed straight-forward, but it took a few emails backwards and forwards to establish exactly what was required.

My answers at each stage, provide a number of alternative versions of what appear to be the same thing - but aren't!

The question itself was essentially "How do I calculate the number of months between two dates?"

My first response to this question used the DATEDIF function as featured in this earlier post.

Assuming that the start date is in cell A1 and the end date is in cell A2, then:

=DATEDIF(A1,A2,"M")

will return the number of WHOLE months between the two dates.

My client then said that they wanted to always round up the number of months.

I then used the "MD" argument of a DATEDIF to identify the remaining days after calculating the whole months, so that I could use and IF statement to add 1 if this remainder was greater than zero:

=DATEDIF(A1,A2,"M")+IF(DATEDIF(A1,A2,"MD")>0,1,0)

Finally, it transpired that what was really required was the number of calendar months touched by the date range, e.g. if the start date was 31st January 2015 and the end date was 1st February 2015, the answer should be 2, as both January and February feature in the date range (with the same dates, our first example would return zero, as there are no whole months and our second would have returned 1, as we rounded the 2 days up to a whole month).

This required a completely different approach, by using the month function to pull out the month from each date, and the year function to pull out the year. The answer would then be the difference between the month numbers, plus 1, plus 12 * the difference in the years, i.e.

=(MONTH(A2)-MONTH(A1)+1)+((YEAR(A2)-YEAR(A1))*12)

Depending upon your specific needs, any one of these formulae might be correct for your requirement!

If you enjoyed this post, go to the top of the blog, where you can subscribe for regular updates and get two freebies "The 5 Excel features that you NEED to know" and "30 Chants for Better Charts".

3 comments:

  1. in the best traditions of multiple cat-skinning methods, I offer the following:

    =DATEDIF(EOMONTH(A1,-1)+1,EOMONTH(A2,0)+1,"M")

    NB that DATEDIF() is available in 2007 and 2010, even though undocumented (not sure about other versions)

    Jim

    ReplyDelete
    Replies
    1. Thanks Jim. I think that should always give the same result. It was always weird the way DATEDIF was a bit of a secret in the older versions!

      Delete
  2. Very useful, thanks!

    ReplyDelete