如何将我的日期和时间转换为日期时间对象?

时间:2011-11-12 00:50:38

标签: ruby-on-rails-3 datetime ruby-on-rails-3.1

如果我有一个日期,例如11/05/2011,以及时间,下午5:30,有一种简单的方法可以将其转换为datetime对象以放入datetime数据库柱?或者我应该以完全不同的方式存储它?

2 个答案:

答案 0 :(得分:3)

> 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 

注意:日期被解析为UTC而没有时区偏移

答案 1 :(得分:0)

这样的事情会起作用。

datetime = DateTime.new(2011,11,05,17,30);
datetime.to_s(:db)

我不确切地知道你是否认为日期和时间是两个单独的字符串