notAnonymousAnymore
notAnonymousAnymore

Reputation: 2687

Using DateTime to find the amount of months (inclusive) between two dates

I have two DateTimes, date1 and date2.

How do I get the difference in months?

2011/01/31 - 2011/02/01 should return 2.
2011/02/01 - 2011/02/01 should return 1.
2011/02/01 - 2012/03/01 should return 14.
etc.

Upvotes: 0

Views: 1700

Answers (2)

Marco
Marco

Reputation: 57593

Try with this:

var diff = 12 * (d2.Year - d1.Year) + (d2.Month - d1.Month) + 1;

Upvotes: 2

Paolo Tedesco
Paolo Tedesco

Reputation: 57302

Try

date2.Month - date1.Month + 1 + (date2.Year - date1.Year) * 12

Upvotes: 5

Related Questions