【问题标题】:How do you convert a Date into a ActiveSupport::TimeWithZone with a particular timezone?如何将日期转换为具有特定时区的 ActiveSupport::TimeWithZone?
【发布时间】:2012-11-14 18:11:51
【问题描述】:

我有一个这样的 Date 对象:

>> the_date
=> Tue, 12 Jun 2012

>> the_date.class
=> Date

以及存储为字符串的时区:

>> tz = "Pacific Time (US & Canada)"
=> "Pacific Time (US & Canada)"

我希望在给定时区的给定日期的午夜生成 ActiveSupport::TimeWithZone(不是 UTC 中给定日期的午夜,然后转换为给定的时区)。到目前为止,我发现这样做的最好方法是非常丑陋:

>> the_time = ActiveSupport::TimeZone.new(tz).parse(the_date.to_s)
=> Tue, 12 Jun 2012 00:00:00 PDT -07:00

>> the_time.class
=> ActiveSupport::TimeWithZone

必须有更好的方法来生成它!有人知道怎么做吗?

【问题讨论】:

    标签: ruby timezone activesupport


    【解决方案1】:

    并没有更好,但与您的解决方案不同:

    the_date.to_time.in_time_zone
    #=> Mon, 11 Jun 2012 22:00:00 UTC +00:00
    
    the_date.to_time.in_time_zone(tz)
    #=> Mon, 11 Jun 2012 15:00:00 PDT -07:00
    
    Time.zone = tz
    #=> "Pacific Time (US & Canada)"
    
    the_date.to_time.in_time_zone
    #=> Mon, 11 Jun 2012 15:00:00 PDT -07:00
    
    the_date.to_time.in_time_zone.end_of_day
    #=> Mon, 11 Jun 2012 23:59:59 PDT -07:00
    
    (the_date.to_time.in_time_zone + 1.day).beginning_of_day
    #=> Tue, 12 Jun 2012 00:00:00 PDT -07:00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 2011-05-07
      • 1970-01-01
      • 2023-04-03
      • 2021-11-19
      • 1970-01-01
      • 2020-01-20
      相关资源
      最近更新 更多