Save DateTime to Database: Timezone Error
I have set
config.time_zone = 'Berlin'
config.active_record.default_timezone = :local
in "application.rb" and restartet WEBrick Webserver an "remigrated" (rake db:drop; rake db:migrate) my database.
If I check Entries in my Database, everything is fine and the "created_at" is correctly saved in my Localtimezone:
sqlite> select created_at from docversions;
2011-08-22 23:27:51.138723
sqlite>
But in this case, this "Local Timezone" doesnt work:
(creat.html.erb)
<%= form_for :token, :url => {:action => "save_token"}, :docversion_id => params[:id] do |f| %>
<%= f.datetime_select :validuntil, :order => [:day, :month, :year, :hour, :minute], :default => 3.days.from_now, %>
<%= f.submit %>
(tokenadmin_controller.rb)
class TokenadminController < ApplicationController
def save_token
@token = Token.new
civildate = DateTime.civil(params[:token]["validuntil(1i)"].to_i,
params[:token]["validuntil(2i)"].to_i,
params[:token]["validuntil(3i)"].to_i,
params[:token]["validuntil(4i)"].to_i,
params[:token]["validuntil(5i)"].to_i)
@token.validuntil = civildate
if @token.save
flash[:notice] = "Token created."
redirect_to :controller => :tokenadmin, :action => :admin
else
flash[:error] = "Token could not be saved!"
redirect_to :controller => "index"
end
end
end
It seems that it would be saved as UTC:
sqlite> select validuntil, created_at from tokens;
2011-08-22 01:44:00.000000|2011-08-22 23:44:20.640434
sqlite>
As you can see, created_at is correctly saved as Localtime, but validuntil is saved +2h (but i have selected the same time as create_at ;-)). I think its +2h because were in a timezone wich is UTC+1 and in DST UTC+2. And were in DST at the moment.
Is that a bug, or did I do something wrong?
Thanks for your help.
UPDATE AFTER POST FROM "BaronVonBraun":
Tha开发者_JAVA技巧nks! Its working now. Databasefield is still "timestamp":
t.timestamp :validuntil
Controller code, wich is use to create a Time-field:
Before:
civildate = DateTime.civil(params[:token]["validuntil(1i)"].to_i,
params[:token]["validuntil(2i)"].to_i,
params[:token]["validuntil(3i)"].to_i,
params[:token]["validuntil(4i)"].to_i,
params[:token]["validuntil(5i)"].to_i)
After:
civildate = Time.parse("#{params[:token]["validuntil(1i)"].to_s}-#{params[:token]["validuntil(2i)"].to_s}-#{params[:token]["validuntil(3i)"].to_s} #{params[:token]["validuntil(4i)"].to_s}:#{params[:token]["validuntil(5i)"].to_s}")
DateTime
objects are in GMT/UTC (+0000 offset) by default.
If you want to store your local timezone along with your date object, I'd suggest using Time
instead of DateTime
, which should use the timezone you've set in your Rails config.
If you need to continue using DateTime
, here is an answer to another question: How do I alter the timezone of a DateTime in Ruby?. However, in that solution, it sets the timezone to a hard offset, meaning it wouldn't handle going in and out of DST.
精彩评论