views:

3226

answers:

4

Rails' ActiveSupport module extends the builtin ruby Time class with a number of methods.

Notably, there is the to_formatted_s method, which lets you write Time.now.to_formatted_s(:db) to get a string in Database format, rather than having to write ugly strftime format-strings everywhere.

My question is, is there a way to go backwards?

Something like Time.parse_formatted_s(:db) which would parse a string in Database format, returning a new Time object. This seems like something that rails should be providing, but if it is, I can't find it.

Am I just not able to find it, or do I need to write it myself?

Thanks

A: 

This talks about parsing times in Rails

J Cooper
Thanks.That post points out that rails itself uses ActiveRecord::ConnectionAdapters::Column#string_to_date (which can be overridden depending on your DB). The fact that it does this, and otherwise falls back to ParseDate implies that rails doesn't provide a function like what I'm looking for
Orion Edwards
As we can now tell that rails doesn't provide this function, that answers the question. I'll write one myself :-)
Orion Edwards
+6  A: 
Tyler Rick
Thanks for posting so much detail. Your DateTime.strptime() reference is very useful for the case where I need to parse a date out of the database that ActiveRecord::Base.connection.select_value() returns as a string.
Lee
Killer answer. I didn't realize the Time.zone = "..." worked. You just saved me a ton of time.
rhh
+2  A: 
>> "2009-09-24".to_date
=> Thu, 24 Sep 2009
>> "9/24/2009".to_date
=> Thu, 24 Sep 2009

Works great unless your date is in some weird format.

eremite
A: 
ActiveSupport::TimeZone.new('UTC').parse('2009-09-23 09:18:08')
=> Wed, 23 Sep 2009 09:18:08 UTC +00:00
Leventix