Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 1.9.3和Ruby 1.8.7之间的日期字符串解析差异_Ruby_Date_Time - Fatal编程技术网

Ruby 1.9.3和Ruby 1.8.7之间的日期字符串解析差异

Ruby 1.9.3和Ruby 1.8.7之间的日期字符串解析差异,ruby,date,time,Ruby,Date,Time,使用Ruby 1.8.7: >> require 'time' >> Time.parse '01/28/2012' => Sat Jan 28 00:00:00 +0200 2012 >> Time.parse '28/01/2012' => ArgumentError: argument out of range 使用Ruby 1.9.3: >> require 'time' >> Time.parse '28/01/

使用Ruby 1.8.7:

>> require 'time'
>> Time.parse '01/28/2012'
=> Sat Jan 28 00:00:00 +0200 2012
>> Time.parse '28/01/2012'
=> ArgumentError: argument out of range
使用Ruby 1.9.3:

>> require 'time'
>> Time.parse '28/01/2012'
=> 2012-01-28 00:00:00 +0200
>> Time.parse '01/28/2012'
=> ArgumentError: argument out of range
在Ruby 1.8.7中,它似乎接受US格式(月/日/年),而在Ruby 1.9.3中,它只接受非US格式(日/月/年)


有没有办法把这种行为改成Ruby 1.8.7

您是否可以选择使用
Time.strtime(“01/28/2012,“%m/%d/%Y”)
代替
Time.parse
?这样,您就可以更好地控制Ruby将如何解析日期

如果没有,则可以使用gems:(例如)使Ruby 1.9 Time.parse的行为类似于Ruby 1.8.7,但仅在绝对必要时使用它

1.9.3-p0 :002 > Time.parse '01/28/2012'
ArgumentError: argument out of range

1.9.3-p0 :003 > require 'american_date'
1.9.3-p0 :004 > Time.parse '01/28/2012'
 => 2012-01-28 00:00:00 +0000 

Ruby 1.9.3似乎已经更改了默认的日期解析格式

在Ruby 1.8.7中

"11/14/2012".to_time
==> Wed Nov 14 00:00:00 UTC 2012
在Ruby 1.9.3中

"11/14/2012".to_time
ArgumentError: invalid date
"14/11/2012".to_time
2012-11-14 00:00:00 UTC
to_时间转换现在接受%d,%m,%Y作为字符串格式

在Ruby 1.9.3中

"11/14/2012".to_time
ArgumentError: invalid date
"14/11/2012".to_time
2012-11-14 00:00:00 UTC
请注意输出的不同格式。Time.now.to_在1.9.3中也返回不同的格式。小心

我看到另一篇文章说,Ruby 1.9.3故意不推荐to_time,但似乎只更改了解析格式

此外

在1.8.7中

Time.parse("11/14/2012", "%m,%d,%Y")
==> Wed Nov 14 06:00:00 UTC 2012
在1.9.3中

Time.parse("11/13/2012", "%m,%d,%Y")
==> ArgumentError: argument out of range

Time.strTime在1.8.7中不存在,仅在1.9.3中存在,因此在对1.9.3进行必要更改后,我看不到使代码向后兼容1.8.7的方法

Ruby只能很好地猜测日期格式,而美国的格式由于模棱两可而令人恼火<代码>01/02/03是…具体是什么<代码>年/月/日<代码>日/月/年
MM/DD/YY
?因为所讨论的代码使用Rails的
String#to_time
,它使用
time.parse
我正在寻找一种解决方案来改变
time.parse
的工作方式。如果它不是现有的代码,我肯定会使用
Time.strtime
——更加健壮。谢谢你指出红宝石美式约会宝石!