Rails在datetime上出现时区问题

时间:2013-08-30 02:56:13

标签: mysql ruby-on-rails ruby-on-rails-3

我有一个带有事件的rails应用程序。我的事件表有一个名为start_date的字段,它是日期时间类型。目前,当我使用chronic保存一个事件来解析start_date字段时,日期会被错误地存储(或者至少返回错误)。

示例:我保存了一个事件,并在start_date的文本字段中输入了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>

4 个答案:

答案 0 :(得分:3)

假设'Central Time (US & Canada)'是正确的(即你不在东部时区),那么:

> 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

答案 1 :(得分:0)

抱歉,我在平板电脑上,所以这必须简短。我有这样的问题,并通过使用类似

的方式纠正它
Time.now.utc 

我确实看到你在application.rb config.time_zone中有这个,所以这可能不起作用。

如果没有,这是一个很好的答案,也许它会有所帮助

Why doesn't `config.time_zone` seem to do anything?

答案 2 :(得分:0)

我有同样的问题,通过在application.rb-

中添加它来解决它
config.time_zone = 'Central Time (US & Canada)'
config.active_record.default_timezone = :local

答案 3 :(得分:0)

我有同样的问题,我只是通过在我的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.