看起來這不是一個Rails的功能,而是一個功能的ActiveSupport。它應該在開箱即用的燈具中正常工作;在例如IRB你需要require 'active_support/time'
。
$ irb
2.2.2 :001 > Time.utc(2015, 7, 1, 10, 5).to_s(:db)
ArgumentError: wrong number of arguments (1 for 0)
from (irb):1:in `to_s'
from (irb):1
from /Users/dmoles/.rvm/rubies/ruby-2.2.2/bin/irb:11:in `<main>'
2.2.2 :002 > require 'active_support/time'
=> true
2.2.2 :003 > Time.utc(2015, 7, 1, 10, 5).to_s(:db)
=> "2015-07-01 10:05:00"
但是請注意,這將下降時區信息:
2.2.2 :004 > Time.now.to_s(:db)
=> "2015-08-14 16:21:47"
而且的ActiveSupport的TimeWithZone
沒有幫助:
$ irb
2.2.2 :001 > require 'active_support/time'
=> true
2.2.2 :002 > time_now = Time.now
=> 2015-08-14 16:31:31 -0700
2.2.2 :003 > time_now_utc = time_now.utc
=> 2015-08-14 23:31:31 UTC
2.2.2 :004 > time_now_with_zone = Time.now.in_time_zone
=> 2015-08-14 16:31:58 -0700
2.2.2 :005 > time_now_utc_with_zone = time_now_utc.in_time_zone
=> 2015-08-14 23:31:31 UTC
2.2.2 :006 > time_now_with_zone.to_s(:db)
=> "2015-08-14 16:31:58"
2.2.2 :007 > time_now_utc_with_zone.to_s(:db)
=> "2015-08-14 23:31:31"
At least in SQLite,這是你要確保你的日期在進入數據庫之前都會一直轉換爲一個時區。
看起來你已經弄明白了:-) –