Tony
Tony

Reputation: 19161

Ruby Time.parse gives me out of range error

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?

Upvotes: 21

Views: 31812

Answers (5)

Oinak
Oinak

Reputation: 1805

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.

Upvotes: 15

Miquel
Miquel

Reputation: 4839

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.

Upvotes: 26

Jonas Elfström
Jonas Elfström

Reputation: 31438

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.

Upvotes: 3

James Avery
James Avery

Reputation: 3012

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

Upvotes: 0

Brandon
Brandon

Reputation: 70002

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

This link may help you parse it.

Upvotes: 12

Related Questions