Reputation: 5174
If I have a date, say 11/05/2011, and a time, 5:30PM, is there an easy way to convert this to a datetime
object to put in a datetime
database column? Or should I store it completely differently?
Upvotes: 0
Views: 744
Reputation: 5060
> rails g model A a:datetime
invoke active_record
create db/migrate/20111112023850_create_as.rb
create app/models/a.rb
invoke test_unit
create test/unit/a_test.rb
create test/fixtures/as.yml
> rake db:migrate
== CreateAs: migrating =======================================================
-- create_table(:as)
-> 0.0011s
== CreateAs: migrated (0.0012s) ==============================================
> rails c
Loading development environment (Rails 3.1.0)
ruby-1.8.7-p299 :001 > rec = A.new
=> #<A id: nil, a: nil, created_at: nil, updated_at: nil>
ruby-1.8.7-p299 :002 > a = "11/05/2011"
=> "11/05/2011"
ruby-1.8.7-p299 :003 > b = "5:30PM"
=> "5:30PM"
ruby-1.8.7-p299 :012 > rec.a = DateTime.parse( "#{a} #{b}" )
=> Sat, 05 Nov 2011 17:30:00 +0000
ruby-1.8.7-p299 :013 > rec.save
SQL (32.2ms) INSERT INTO "as" ("a", "created_at", "updated_at") VALUES (?, ?, ?) [["a", Sat, 05 Nov 2011 17:30:00 UTC +00:00], ["created_at", Sat, 12 Nov 2011 02:43:05 UTC +00:00], ["updated_at", Sat, 12 Nov 2011 02:43:05 UTC +00:00]]
=> true
note: the date was parsed as UTC without a timezone offset
Upvotes: 3
Reputation: 4295
Something like this would work.
datetime = DateTime.new(2011,11,05,17,30);
datetime.to_s(:db)
I don't know exactly if you meant the date and time were two separate strings
Upvotes: 0