当使用Time.strptime和Date.strptime解析“某些日期”(在Ruby中)时,它们有不同的行为。
例如,如果我们试图转换“2月30日”(一个不存在的日期),我们有:
Time.strptime('30 Feb 2015', '%d %b %Y') # will result in this date: 2015-03-02
Date.strptime('30 Feb 2015', '%d %b %Y') # ArgumentError: invalid date同时,试图解析"32 Feb“会导致两个类的错误。
Time.strptime('32 Feb 2015', '%d %b %Y') # ArgumentError: invalid strptime format - `%d %b %Y'
Date.strptime('32 Feb 2015', '%d %b %Y') # ArgumentError: invalid date行为不同的原因是什么?为什么时间“试图调整”无效的日期?
发布于 2015-07-10 08:42:25
好的,我做了更多的调查,发现了一些关于这个主题的“问题”:https://bugs.ruby-lang.org/issues/9549和主要的:https://bugs.ruby-lang.org/issues/10588。
Time这样做是有原因的。正如田中明所言:
难以确定无效日期/时间。应用程序几乎是不可能的,因为它取决于各种因素:月份、闰年、夏季时间、闰秒、时区定义的变化。 有时,应用程序需要在给定年份/月/日/小时/分钟/秒附近设置一个时间对象。
因此,Time试图补偿可能的“几乎正确”时间。这就是为什么它成功地解析了这一点:Time.strptime('29 Mar 2015 3:30:00 +02000', '%d %b %Y %T %z')到2015-03-29 04:30:00 +0300 (由于夏令时间,3:30是2015年3月29日的无效时间,从3:00到4:00)
https://stackoverflow.com/questions/31317055
复制相似问题