Thursday, February 17, 2011

Calculating Months

I have an application where the user selects the dates of a first statement and a last statement. Example, first statement = 1/1/08, last statement = 12/1/08, should equal 12 statements.

However, when using the following code, the result is 11:

numPayments = DateDiff(DateInterval.Month, CDate(.FeeStartDate), CDate(.FeeEndDate))

Is there another way to calculate this, or do I have to be stuck with adding 1 to the result?

From stackoverflow
  • Add 1, as you write. ;)

    The difference between 1/1/2008 and 12/1/2008 is 11 months. No changing that. ;)

  • Well, the number of months between Jan 1st and Dec 1st is 11... what you're looking for is the difference of months +1. So just add one :)

  • Also, the DateDiff function you're using is a VB6 hold-over. Better to express it like this:

    numPayments = (Date.Parse(.FeeEndDate) - Date.Parse(.FeeStartDate)).TotalMonths + 1
    
  • Yes, you'd always have to add one though you may be able to add one to the end date or subtract one from the start date to also get this effect. Consider the case where the start and end dates are the same. Their difference is 0 but you'd still want 1 statement to show just to note one odd case.

0 comments:

Post a Comment