Ruby Time.parse gives me out of range error
-
03-07-2019 - |
Question
I am using Time.parse to create a Time object from a string.
For some reason
Time.parse("05-14-2009 19:00")
causes an argument our of range error, whereas
Time.parse("05-07-2009 19:00")
does not
Any ideas?
Solution
My guess would be that its expecting the second part of the string (the 14) to be the month.
OTHER TIPS
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
It will solve your problem and will probably be faster than Time.parse
.
EDIT:
Looks like they took strptime
from Time class, but it called Date.strptime
anyway. If you are on Rails you can do:
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])
It's because of the heuristics of Time#parse
.
And it's due to anglo-american formats.
With dashes '-' it expects mm-dd-yyyy, with slashes '/' it expects dd/mm/yyyy.
This behaviour changes intentionally in 1.9. to accomplish eur, iso and jp date standards.
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.
It is probably expecting Day-Month-Year format, so your first value is trying to specify the 5th day of the 14th month.