[英]Rails issues with timezone on datetime
我有一個帶有事件的rails應用程序。 我的事件表有一個名為start_date
的字段,它是datetime類型。 目前,當我使用chronic保存事件來解析start_date字段時,日期會被錯誤地存儲(或者至少返回錯誤)。
示例:我保存了一個事件,並在start_date的文本字段中,我9/14/13 at 9am
進入9/14/13 at 9am
。 它保存了數據,刷新了頁面,文本字段中的值是9/14/13 at 11am
。 mysql表中的值是2013-09-14 16:00:00
。
這里發生了什么? 這只發生在我的服務器上,而不是在本地運行時。
application.rb中:
config.time_zone = 'Central Time (US & Canada)'
車型/ event.rb:
class Event < ActiveRecord::Base
belongs_to :user
attr_accessible :description, :name, :start_date_string
validate :name_not_blank
validate :start_date_not_blank
# Validate that the name is not blank
def name_not_blank
errors.add(:name, "Name can't be blank") unless !name.blank?
end
# Validate that the name is not blank
def start_date_not_blank
errors.add(:start_date, "Date and Time can't be blank") unless !start_date.blank?
end
# getter
def start_date_string
@start_date_string || start_date.in_time_zone.try(:strftime, "%m/%d/%Y at %I:%M %P")
end
# setter
def start_date_string=(value)
@start_date_string = value
self.start_date = parse_start_date
end
# parse the start_date
def parse_start_date
Chronic.parse(start_date_string)
end
end
助手/ application_helper.rb:
# Formats a date to words (i.e. March 20, 1980 at 10:00 am)
def spell_date_and_time(date)
date.strftime("%B %d, %Y at %I:%M %P")
end
edit.html.erb
<span class="timestamp"><%= spell_date_and_time(event.start_date) %></span>
假設'Central Time (US & Canada)'
是正確的(即您不在東部時區),那么:
in_time_zone
,rails會使用當前的Time.zone為你做這件事 > Time.zone = "UTC" > Chronic.time_class = Time.zone > Chronic.parse("June 15 2006 at 5:45 AM") => Thu, 15 Jun 2006 05:45:00 UTC +00:00
您可以將Chronic.time_class = Time.zone
放在config/initializers/chronic.rb
Chronic.time_class = Time.zone
中
對不起,我在平板電腦上,所以這必須簡短。 我有這樣的問題,並通過使用類似的東西糾正它
Time.now.utc
我確實看到你在application.rb config.time_zone中有這個,所以這可能不起作用。
如果沒有,這是一個很好的答案,也許它會有所幫助
我有同樣的問題,通過在application.rb-中添加它來解決它。
config.time_zone = 'Central Time (US & Canada)'
config.active_record.default_timezone = :local
我有同樣的問題,我只是通過在我的application.rb中注釋這一行來修復它:
config.active_record.default_timezone = :local
我是根據我在application.rb中讀到的內容完成的。
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.