问题
I'm trying to compare what the user selects for a start date and end date to the current time to prevent the user from selecting a time in the past. It works except you have to pick a time, in my case, 4 hours ahead in order for it to pass the validation.
View:
datetime_select(:start_date, ampm: true)
Controller:
if self.start_date < DateTime.now || self.end_date < DateTime.now
errors.add(:date, 'can not be in the past.')
end
self.start_date is returning my current time but in utc which is wrong. DateTime.now is returning my current time but with an offset of -0400 which is correct.
Example:
My current time is 2013-10-03 09:00:00.000000000 -04:00
self.start_date is 2013-10-03 09:00:00.000000000 Z
DateTime.now is 2013-10-03 09:00:00.000000000 -04:00
Why is this happening and what would be the best way to fix it?
回答1:
you can do something like this
around_filter :set_time_zone
private
def set_time_zone
old_time_zone = Time.zone
Time.zone = current_user.time_zone if logged_in?
yield
ensure
Time.zone = old_time_zone
end
you can also do this
adding following to application.rb works
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = 'Eastern Time (US & Canada)'
回答2:
I ended up fixing it by converting the start_date to a string and back to time. It was weird that I needed :local, as the documentation on to_time says it is the default, but it only works when it is present.
def not_past_date
current_time = DateTime.now
start_date_selected = self.start_date.to_s.to_time(:local)
end_date_selected = self.start_date.to_s.to_time(:local)
if start_date_selected < current_time || end_date_selected < current_time
errors.add(:date, 'can not be in the past.')
end
end
来源:https://stackoverflow.com/questions/19163176/rails-datetime-select-posting-my-current-time-in-utc