views:

2064

answers:

5

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?

+3  A: 

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.

Brandon
A: 

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

James Avery
+5  A: 
Miquel
strptime looks cool but I get an undefined method for Time.strptime and I need a time object
Tony
...here is the usage Time.strptime(date_time['value'], "%m-%d-%Y %H:%M")
Tony
Looks like strptime does not exist in Time anymore, see edit for alternative
Miquel
thanks miguel, that solution looks good. i ended up using this statement: fixed_date_time = "#{$2}-#{$1}-#{$3} #{$4}:#{$5}" if date_time['value'] =~ /(\d{2})-(\d{2})-(\d{4})\s(\d{2}):(\d{2})/ because i saw your post late. i don't plan on changing it because it works and it may even be faster. anyway, voted you up but had to give the answer to the first commenter since his link solved my problem.
Tony
I don't think this solution is faster as it has to call _parse anyway, parse implementation use heuristics checking a lot of cases. Additionally, your code will fail when 1.9 is out as they changed to use ISO date formats. My solution will not fail as uses the ruby standard date formating mechanisms.
Miquel
+3  A: 

It's beacuse 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 behaivour CHANGES intentionally in 1.9. to accomplish eur,iso and jp Date standadrs

Fer
+1  A: 

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.

Jonas Elfström