1

I get different results when I add months to a DateTime in different increments. Is this a bug?

> start_date = DateTime.strptime("03/31/2001", "%m/%d/%Y")
#=> Sat, 31 Mar 2001 00:00:00 +0000
> start_date + 3.months
#=> Sat, 30 Jun 2001 
> d1 = start_date + 3.months
#=> Sat, 30 Jun 2001 
> d2 = d1 + 3.months
#=> Sun, 30 Sep 2001 
> d3 = d2 + 3.months
#=> Sun, 30 Dec 2001 
> start_date + 9.months
#=> Mon, 31 Dec 2001

So, (((start_date + 3.months) + 3.months) + 3.months) != start_date + 9.months?

Solution (based on accepted answer below): using d3.end_of_month gives me the expected 31 December instead of 30 December.

Anand
  • 3,690
  • 4
  • 33
  • 64

1 Answers1

3

This is not a bug, but rather a result of June having 30 days. When you add the first 3 months, it takes you to the end of June, the 30th. Subsequent additions will continue to end up on the 30th. When you add 9 months, you jump straight to December, a month that has 31 days. If you start in June, you will see consistent results, unless you happen to end up in February...

Brad Werth
  • 17,411
  • 10
  • 63
  • 88
  • Thanks. I have a loop in my app that increments by three months at a time, and expects to go to the end of each 3 months for the exit condition to work - is there a (non-manual) way to achieve that? – Anand Aug 21 '15 at 06:09