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

后端 未结 3 2042
不知归路
不知归路 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条回答
  •  渐次进展
    2020-12-29 20:41

    This is a weird feature of ActiveSupport time extensions.

    > 6.months == 180.days
    => true 
    

    but when you do date math with months, they are considered calendar months, not 30-day periods. Check this out:

    > Date.today - 180.days + 180.days
    => Mon, 31 Oct 2011 
    

    See https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/time/calculations.rb#L277 and dig further from there.

提交回复
热议问题