在Rails中操作TimeWithZone

时间:2013-12-10 06:06:25

标签: ruby-on-rails datetime

我有这个rails应用程序,需要在其中一个表单中捕获时间日期和时区,例如: 时区:'香港'为字符串 日期时间:'31 / 12/2013 23:59'为字符串

应用程序的默认时区设置为“墨尔本”,应用程序当前接受日期时间并自动转换为“2013-12-31 23:59:00 +1100”,其中+1100是墨尔本时间区域偏移,夏令时。

我想要申请:
1)以'31 / 12/2013 23:59:00'为所选时区的时间,即香港 2)将香港时间转换为墨尔本时间,即'31 / 12/2013 23:59:00 +0800'至'01 / 01/2014 02:59 +1100'并持续存入数据库。
3)在2)的转换过程中,需要注意夏令时。

我已经写了下面的代码将完全按照我想要它做的只在控制器中工作。但是,当我使用before_create过滤器

将其移动到模型时,它不起作用
time_zone = ActiveSupport::TimeZone.new(params[:time_zone])
date_time = DateTime.strptime(params[:date_time], '%d/%m/%Y %H:%M')

new_date_time = date_time.change(offset: time_zone.formatted_offset(false))
melbourne_date_time = new_date_time.in_time_zone(Time.zone)

它在模型中不起作用的原因是在控制器中,我手动将日期时间字符串解析为日期时间对象。但是在模型中,rails会自动将日期时间字符串转换为TimeWithZone对象...因此,无法真正改变对象......

我做了一些谷歌搜索,仍然无法找到确切的解决方案。

任何帮助将不胜感激!

P.S。该应用程序在Rails 3.2.12上。我打算在附带模型的before_create过滤器的方法中运行转换。

干杯

2 个答案:

答案 0 :(得分:0)

您只需为rails应用程序设置默认time_zone

  • 打开config/application.rb

  • 使用此

    设置默认time_zone
    class Application < Rails::Application
    
      config.time_zone = 'Hong Kong'
      config.active_record.default_timezone = 'Hong Kong'
    
    end
    

答案 1 :(得分:0)

我找到了一种(脏?)方式来存档我想要的模型。

表单中的用户输入: 时区 - '香港'为弦乐, 日期时间 - '31 / 12/2013 23:59:00'为字符串

config.time_zone = 'Melbourne'# in config/application.rb

self.time_zone # 'Hong Kong' as String
self.date_time # '31/12/2013 23:59:00 +1100' as TimeWithZone

class MyClass < ActiveRecord::Base
  before_create :populate_date_time_with_zone
  def populate_date_time_with_zone
    original_tz = Time.zone # Capture the system default timezone, 'Melbourne'
    Time.zone = self.time_zone # Change the timezone setting for this thread to 'Hong Kong'
    dt = Time.zone.parse(self.date_time.strftime('%d/%m/%Y %I:%M%p')) #Dirty??
    self.date_time = dt.in_time_zone(original_tz) # '01/01/2014 02:59:00 +1100' as TimeWith Zone
  end
end

有没有比将日期时间打印到字符串中更好的方法,而不是使用更改的Time.zone再次解析它?