为什么是Date.today - 6.months + 6.months!= Date.today? [英] Why is Date.today - 6.months + 6.months != Date.today?

查看:74
本文介绍了为什么是Date.today - 6.months + 6.months!= Date.today?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,在万圣节:

In Ruby, on Halloween:

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

我们需要更新Ruby的日期实现吗?其他语言有同样的问题吗?

Do we need to update Ruby's date implementation? Do other languages have the same issue?

推荐答案

如果您进行任何没有31天的任何月份,即3个月就可以正常工作,但是1个月,或6个,或8个都会发生这种情况)。

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).

如果你执行 Date。今天 - 1.month ,看起来Rails看到9/31/2011是不是有效的日期,所以它踢了一个额外的一天,使其成为有效的日期。但是,当您从9月底开始一个月前,将于10/30/2011离开,因为这是有效的日期。基本上,Rails只是尝试增加(或减少)月份字段,只要它是有效的日期,它将不会调整日期字段。

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.

一种方法解决这个问题的方法是在日期上使用 .end_of_month (或 .beginning_of_month )方法对象在Rails中,以确保您一直得到结束或一个月的开始。

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.

这篇关于为什么是Date.today - 6.months + 6.months!= Date.today?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆