Why is Date.today - 6.months + 6.months != Date.today?

后端 未结 3 2034
不知归路
不知归路 2020-12-29 20:15

In Ruby, on Halloween:

Date.today - 6.months + 6.months != Date.today

Do we need to update Ruby\'s date implementation? Do other languages

3条回答
  •  -上瘾入骨i
    2020-12-29 21:00

    This happens if you do it to any month that doesn't have 31 days (i.e. 3 months would work just fine, but 1 month, or 6, or 8 would all make this happen).

    If you do Date.today - 1.month, it looks like Rails sees that 9/31/2011 isn't a valid date, so it kicks it back an extra day to make it a valid date. However, when you go one month forward from the end of September, it'll leave it at 10/30/2011 since that's a valid date. Basically, Rails just tries to increment (or decrement) the month field and as long as it's a valid date, it won't adjust the day field.

    One way to work around this is to use the .end_of_month (or .beginning_of_month) method on a Date object in Rails to make sure you're consistently getting the end or beginning of a month.

提交回复
热议问题