【问题标题】:How to taking time zone into account when using Date#to_time method使用 Date#to_time 方法时如何考虑时区
【发布时间】:2016-10-22 08:49:21
【问题描述】:

我有一个具有 Tokyo(+0900) 时区的 Rails 项目。

操作系统本地时区为Bangkok(+0700)

Date#to_time 方法不考虑时区。

Date.current.to_time
2016-06-21 00:00:00 +0700

我现在正在使用Time.zone.parse 方法:

Time.zone.parse(Date.current.to_s)
Tue, 21 Jun 2016 00:00:00 JST +09:00

有没有更好的方法将日期转换为具有正确时区的时间?

时区

Time.zone
#<ActiveSupport::TimeZone:0x007fa8402f86f0 @name="Tokyo", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Asia/Tokyo>, @current_period=#<TZInfo::TimezonePeriod: #<TZInfo::TimezoneTransitionDefinition: #<TZInfo::TimeOrDateTime: -578044800>,#<TZInfo::TimezoneOffset: 32400,0,JST>>,nil>>

config/application.rb

module MyProject
  class Application < Rails::Application
   config.time_zone = 'Tokyo'
  end
end

【问题讨论】:

  • 你知道TZInfo吗?它被认为是健壮的(遵循 DST),你会说TZInfo::Timezone.get('Asia/Bangkok').now
  • 该方法可能很方便,但我的问题是如何将Date实例转换为Time实例考虑时区。

标签: ruby-on-rails timezone


【解决方案1】:

【讨论】:

    【解决方案2】:

    to_time 默认采用本地时区转换时区时间,参数中只接受 :local 或 :utc 时区。所以你必须先设置时区,然后再将.to_time 应用于Date 对象。

    Time.zone = "Tokyo"
    irb(main):046:0> Date.current.to_time
    => Tue, 21 Jun 2016 09:00:00 JST +09:00
    

    或者您可以使用.use_zone 使用该块来为特定块保留该设置的时区。

    irb(main):046:0> Time.use_zone("Tokyo"){Date.current.to_time}
    => Tue, 21 Jun 2016 09:00:00 JST +09:00
    

    以上结果将始终为您提供与UTC 相关的时间,因此将根据所选时区添加时间。如果您希望将其设置为一天的开始,您可以使用beginning_of_day

    Time.zone = "Tokyo"
    irb(main):048:0> Date.current.to_time.beginning_of_day
    => Tue, 21 Jun 2016 00:00:00 JST +09:00
    
    irb(main):049:0> Time.use_zone("Tokyo"){ Date.current.to_time.beginning_of_day }
    => Tue, 21 Jun 2016 00:00:00 JST +09:00
    

    使用Date对象进行Time Zone操作并不是更好的方法,始终使用Time对象来处理Time Zone

    Time.zone = "东京"

    irb(main):050:0> Time.zone.now.beginning_of_day
    => Tue, 21 Jun 2016 00:00:00 ICT +09:00
    
    irb(main):051:0> Time.use_zone("Tokyo"){ Time.zone.now.beginning_of_day }
    => Tue, 21 Jun 2016 00:00:00 JST +09:00
    

    Do’s and Don’ts of Rails Timezones

    【讨论】:

    • 是的,我设置了时区,但是#to_time 方法没有反映它。 Time.zone = 'Tokyo'; Date.current.to_time #=&gt; 2016-06-22 00:00:00 +0700.
    • 您能否在分配时区后检查Time.zone 来验证时区设置是否正确。
    • 能否将代码粘贴到您设置时区的位置?
    • 抱歉,回复晚了。我添加了有关Time.zone 以及如何设置时区的信息。
    猜你喜欢
    • 2010-11-06
    • 1970-01-01
    • 2020-09-12
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 2015-09-22
    相关资源
    最近更新 更多