Ruby Time.parse 给我超出范围的错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/800118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:11:28  来源:igfitidea点击:

Ruby Time.parse gives me out of range error

ruby-on-railsrubydatetimetime

提问by Tony

I am using Time.parse to create a Time object from a string.

我正在使用 Time.parse 从字符串创建一个 Time 对象。

For some reason

因为某些原因

Time.parse("05-14-2009 19:00")

causes an argument our of range error, whereas

导致参数 our of range 错误,而

Time.parse("05-07-2009 19:00")

does not

才不是

Any ideas?

有任何想法吗?

采纳答案by Brandon

My guess would be that its expecting the second part of the string (the 14) to be the month.

我的猜测是它期望字符串的第二部分(14)是月份。

This link may help you parse it.

此链接可能会帮助您解析它。

回答by Miquel

If you know the format of the string use:

如果您知道字符串的格式,请使用:

Time.strptime(date, format, now=self.now) {|year| ...}   

http://www.ruby-doc.org/core-1.9/classes/Time.html#M000266

http://www.ruby-doc.org/core-1.9/classes/Time.html#M000266

It will solve your problem and will probably be faster than Time.parse.

它将解决您的问题,并且可能比Time.parse.

EDIT:

编辑:

Looks like they took strptimefrom Time class, but it called Date.strptimeanyway. If you are on Rails you can do:

看起来他们是strptime从 Time 课上学来的,但它还是调用Date.strptime了。如果你在 Rails 上,你可以这样做:

Date.strptime("05-14-2009 19:00","%m-%d-%Y %H:%M").to_time

if you use pure ruby then you need:

如果您使用纯红宝石,那么您需要:

require 'date'
d=Date._strptime("05-14-2009 19:00","%m-%d-%Y %H:%M")

Time.utc(d[:year], d[:mon], d[:mday], d[:hour], d[:min], 
         d[:sec], d[:sec_fraction], d[:zone])

See also: Date and Time formating issues in Ruby on Rails.

另请参阅:Ruby on Rails 中的日期和时间格式问题

回答by Oinak

It's because of the heuristics of Time#parse.

这是因为Time#parse.

And it's due to anglo-american formats.

这是由于英美格式。

With dashes '-' it expects mm-dd-yyyy, with slashes '/' it expects dd/mm/yyyy.

破折号“-”预期为mm-dd-yyyy,斜线“/”预期为dd/mm/yyyy。

This behaviour changesintentionally in 1.9. to accomplish eur, iso and jp date standards.

此行为在 1.9 中有意更改。达到 eur、iso 和 jp 日期标准。

回答by Jonas Elfstr?m

You probably do not need it to solve this problem but I still recommend checking out the natural language date/time parser Chronic, it has saved me a lot of work a couple of times.

您可能不需要它来解决这个问题,但我仍然建议查看自然语言日期/时间解析器Chronic,它为我节省了很多工作。

回答by James Avery

It is probably expecting Day-Month-Year format, so your first value is trying to specify the 5th day of the 14th month.

它可能需要 Day-Month-Year 格式,因此您的第一个值是尝试指定第 14 个月的第 5 天。