Ruby Date.parse 异常
我在 Ruby 的 Date.parse 中发现了一个奇怪的行为,想知道是否有人可以阐明这一点。
今天的日期是 2011 年 10 月 17 日。
irb(main):027:0> Date.parse("11-20").to_s
=> "2011-10-11"
irb(main):028:0> Date.parse("11/20").to_s
=> "2011-11-20"
irb(main):029:0> Date.parse("1-20").to_s
=> "2011-10-20"
irb(main):032:0> Date.parse("1/20").to_s
=> "2011-01-20"
irb(main):030:0> Date.parse("9-20").to_s
=> "2011-10-20"
irb(main):035:0> Date.parse("9/20").to_s
=> "2011-09-20"
irb(main):031:0> Date.parse("9-10").to_s
=> "2011-10-10"
irb(main):033:0> Date.parse("9/10").to_s
=> "2011-09-10"
irb(main):042:0> Date.parse("1-20-1997").to_s
ArgumentError: invalid date
from /usr/lib/ruby/1.8/date.rb:956:in `new_by_frags'
from /usr/lib/ruby/1.8/date.rb:1000:in `parse'
from (irb):42
from /usr/lib/ruby/1.8/date.rb:1578
irb(main):043:0> Date.parse("1/20/1997").to_s
=> "1997-01-20"
我不确定它如何解释连字符与斜杠。斜杠行为对我来说非常有意义。但连字符的行为很奇怪。 parse 在连字符的情况下做了什么?
I've found a strange behavior in Ruby's Date.parse wondering if someone could shed light on.
Today's date is 17 Oct 2011.
irb(main):027:0> Date.parse("11-20").to_s
=> "2011-10-11"
irb(main):028:0> Date.parse("11/20").to_s
=> "2011-11-20"
irb(main):029:0> Date.parse("1-20").to_s
=> "2011-10-20"
irb(main):032:0> Date.parse("1/20").to_s
=> "2011-01-20"
irb(main):030:0> Date.parse("9-20").to_s
=> "2011-10-20"
irb(main):035:0> Date.parse("9/20").to_s
=> "2011-09-20"
irb(main):031:0> Date.parse("9-10").to_s
=> "2011-10-10"
irb(main):033:0> Date.parse("9/10").to_s
=> "2011-09-10"
irb(main):042:0> Date.parse("1-20-1997").to_s
ArgumentError: invalid date
from /usr/lib/ruby/1.8/date.rb:956:in `new_by_frags'
from /usr/lib/ruby/1.8/date.rb:1000:in `parse'
from (irb):42
from /usr/lib/ruby/1.8/date.rb:1578
irb(main):043:0> Date.parse("1/20/1997").to_s
=> "1997-01-20"
I'm not sure how it's interpreting the hyphen versus the slash. The slash behavior makes perfect sense to me. But the hyphen behavior is odd. What's parse doing in the hyphen case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Date.parse
内部使用名为_parse
的方法,您可以在此处查看:http://www.ruby-doc.org/stdlib-1.9.2/libdoc/date/rdoc/Date.html#method-c-_parse
如果你把前面的年份:
如果您查看
Date.parse
的默认参数,即str='-4712-01-01'
,这是有道理的。没有年份的连字符形式很奇怪,我个人不会使用它。Date.parse
internally uses a method called_parse
, which you can see here:http://www.ruby-doc.org/stdlib-1.9.2/libdoc/date/rdoc/Date.html#method-c-_parse
Your last example works if you put the year in front:
This makes sense if you look at the default argument to
Date.parse
, which isstr='-4712-01-01'
. The hyphen form without a year is weird and I personally wouldn't use it.您可能想考虑使用 chronic gem。
You may want to look in to using the chronic gem.