我刚刚发现了 Rails 日期格式中的错误吗?
在尝试解析日期时,我已经绞尽脑汁了几个小时:
Date.today.to_s
=> "06/07/2011"
Date.today
=> Tue, 07 Jun 2011
Date.parse Date.today.to_s
=> Wed, 06 Jul 2011
Date::DATE_FORMATS[:default]
=> "%m/%d/%Y"
to_s 的默认格式与解析的默认格式不同?他们为什么要这样对我?
将 Rails 3.0.5 与 Ruby 1.9.2-p180 结合使用
更新 因此,感谢您的回答,我意识到 DATE_FORMATS 是 Rails 的东西,而 Date.format 使用 ruby 库(正确吗?)。有没有办法使用默认的 DATE_FORMAT 解析日期/时间而不使用 strptime ?
In trying to parse a date, I have been racking my brain for hours:
Date.today.to_s
=> "06/07/2011"
Date.today
=> Tue, 07 Jun 2011
Date.parse Date.today.to_s
=> Wed, 06 Jul 2011
Date::DATE_FORMATS[:default]
=> "%m/%d/%Y"
The default format for to_s is different than the default format for parsing? Why would they do this to me?
Using Rails 3.0.5 with Ruby 1.9.2-p180
UPDATE
So thanks to your answers, I realize that the DATE_FORMATS is a rails thing while Date.format is using the ruby library (correct?). Is there a way then to parse dates/times with the default DATE_FORMAT without using strptime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常,
Date.today.to_s
将返回“2011-06-07”,但由于您设置了默认日期格式,因此它会使用“06/07/2011”。Date.parse
很容易识别 YYYY-MM-DD 格式,但是当它看到 06/07/2011 时,它认为这实际上是 DD/MM/YYYY(而不是您期望的 MM/DD/YYYY) -- 请记住,Date.parse
对您设置的 Rails 默认日期格式一无所知。默认日期格式仅适用于 Rails 的输出。Date.to_s
)。您可以强制它解析 MM/DD/YYYY 日期,如下所示:
Normally,
Date.today.to_s
would return "2011-06-07", but since you set a default date format, it's using "06/07/2011" instead.Date.parse
easily recognizes the YYYY-MM-DD format, but when it sees 06/07/2011 it thinks that's really DD/MM/YYYY (not MM/DD/YYYY as you're expecting -- keep in mind thatDate.parse
knows nothing about Rails' default date format you set. The default date format is only for Rails' outputting ofDate.to_s
).You can force it to parse a MM/DD/YYYY date like this:
我猜想 to_s 方法使用 区域设置选项 确定日期的书写方式。
但我不明白这是一个问题。 Date.parse 使用启发式方法来解析日期,因此有时会出错。
I would guess that the to_s method uses a locale option to determine how to write the date.
I dont see how this is an issue though. Date.parse uses heuristics to parse the date so sometimes it will get it wrong.
Chronic gem(链接)解决了几乎所有日期解析问题(是的,它们可能非常烦人)。
The Chronic gem (link)solves pretty much all date parsing issues (and yes, they can be quite annoying).