Time From String

Is there any Ruby / Rails way to take a string and convert it to time?
timefstr

Specificallc,y I’d like to convert iso 8601 fromats to Ruby Time objects
or ActiveRecord time fields.

On Fri, Jan 20, 2006 at 06:48:47AM +0100, List R. wrote:

Is there any Ruby / Rails way to take a string and convert it to time?
timefstr

Specificallc,y I’d like to convert iso 8601 fromats to Ruby Time objects
or ActiveRecord time fields.

require ‘time’
=> true

Time.parse ‘9:24’
=> Thu Jan 19 09:24:00 CST 2006

Time.parse ‘9:24 pm’
=> Thu Jan 19 21:24:00 CST 2006

Time.parse ‘9:24 am’
=> Thu Jan 19 09:24:00 CST 2006

Time.parse ‘9:24am’
=> Thu Jan 19 09:24:00 CST 2006

Time.parse ‘9:24pm’
=> Thu Jan 19 21:24:00 CST 2006

Time.parse ‘924’
=> Thu Jan 19 23:22:31 CST 2006

------------------------------------------------------------ Time::parse
Time::parse(date, now=Time.now) {|year| …}

 Parses +date+ using ParseDate.parsedate and converts it to a Time
 object.

 If a block is given, the year described in +date+ is converted by
 the block. For example:

     Time.parse(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) 

: y}

 If the upper components of the given time are broken or missing,
 they are supplied with those of +now+. For the lower components,
 the minimum values (1 or 0) are assumed if broken or missing. For
 example:

     # Suppose it is "Thu Nov 29 14:33:20 GMT 2001" now and
     # your timezone is GMT:
     Time.parse("16:30")     #=> Thu Nov 29 16:30:00 GMT 2001
     Time.parse("7/23")      #=> Mon Jul 23 00:00:00 GMT 2001
     Time.parse("Aug 31")    #=> Fri Aug 31 00:00:00 GMT 2001

 Since there are numerous conflicts among locally defined timezone
 abbreviations all over the world, this method is not made to
 understand all of them. For example, the abbreviation "CST" is used
 variously as:

     -06:00 in America/Chicago,
     -05:00 in America/Havana,
     +08:00 in Asia/Harbin,
     +09:30 in Australia/Darwin,
     +10:30 in Australia/Adelaide,
     etc.

 Based on the fact, this method only understands the timezone
 abbreviations described in RFC 822 and the system timezone, in the
 order named. (i.e. a definition in RFC 822 overrides the system
 timezone definition.) The system timezone is taken from
 +Time.local(year, 1, 1).zone+ and +Time.local(year, 7, 1).zone+. If
 the extracted timezone abbreviation does not match any of them, it
 is ignored and the given time is regarded as a local time.

 ArgumentError is raised if ParseDate cannot extract information
 from +date+ or Time class cannot represent specified date.

 This method can be used as fail-safe for other parsing methods as:

   Time.rfc2822(date) rescue Time.parse(date)
   Time.httpdate(date) rescue Time.parse(date)
   Time.xmlschema(date) rescue Time.parse(date)

 A failure for Time.parse should be checked, though.

marcel