Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Time.parse gives me out of range error

Tags:

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?

like image 629
Tony Avatar asked Apr 28 '09 22:04

Tony


2 Answers

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])

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

like image 199
Miquel Avatar answered Nov 18 '22 09:11

Miquel


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.

like image 36
Oinak Avatar answered Nov 18 '22 08:11

Oinak