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?
-
My guess would be that its expecting the second part of the string (the 14) to be the month.
-
It is probably expecting Day-Month-Year format, so your first value is trying to specify the 5th day of the 14th month.
-
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: http://blog.nominet.org.uk/tech/2007/06/14/date-and-time-formating-issues-in-ruby-on-rails/
Tony : strptime looks cool but I get an undefined method for Time.strptime and I need a time objectTony : ...here is the usage Time.strptime(date_time['value'], "%m-%d-%Y %H:%M")Miquel : Looks like strptime does not exist in Time anymore, see edit for alternativeTony : 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.Miquel : 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. -
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
-
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.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.