rails DateTime月份加法不一致

rails DateTime months addition not consistent

当我以不同的增量将月份添加到 DateTime 时,我得到了不同的结果。这是一个错误吗?

> 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

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

解决方案(基于下面接受的答案):使用 d3.end_of_month 给我预期的 31 December 而不是 30 December.

这不是错误,而是 6 月有 30 天的结果。当您添加前 3 个月时,它会将您带到 6 月底,即 30 日。后续补充将继续在30日结束。当您添加 9 个月时,您会直接跳到 12 月,该月有 31 天。如果您从 6 月开始,您将看到一致的结果,除非您恰好在 2 月结束...