Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How convert a string into a ActiveSupport::TimeWithZone?

I need to update a field (called updated_at). The field in MySQL is of type datetime, and the class is ActiveSupport::TimeWithZone. But the dates are strings like "10/17/2008". I used "10/17/2008".to_date (And I intend .to_time and .to_datetime), and even if in console the ActiveRecord class save successfully, the field in the database still is the current date.

like image 682
Mangano Avatar asked Apr 09 '10 15:04

Mangano


2 Answers

OK.. let's take them one at the time.

First, it is not recommended to set a field name updated_at, since this is a "magic" field that is automatically populated by Rails.

If you want to disable this functionality, you may:

class Foo < ActiveRecord::Base
  self.record_timestamps = false
end

in your class, but this will also disable created_at fields.

The best option is to add a new field (e.g. my_updated_at) as date in the database, and then Rails will automatically handle conversions, meaning that the next snippet will work:

Foo.new({:my_updated_at => "10/17/2008"})

Second, the answer on how to parse a string to ActiveSupport::TimeWithZone is:

ActiveSupport::TimeZone['UTC'].parse("10/17/2008")

but I don't think this will help you (of course, change UTC with your current date/time).

like image 129
Vlad Zloteanu Avatar answered Nov 06 '22 06:11

Vlad Zloteanu


Simply

date_as_string = "2008-10-17"
ActiveSupport::TimeZone['UTC'].parse(date_as_string)

# => Fri, 17 Oct 2008 00:00:00 UTC +00:00


And just to confirm that it worked..

ActiveSupport::TimeZone['UTC'].parse(date_as_string).class

# => ActiveSupport::TimeWithZone
like image 43
stevec Avatar answered Nov 06 '22 05:11

stevec