【问题标题】:Specify UTC Offset instead of timezone to ActiveSupport::TimeWithZone为 ActiveSupport::TimeWithZone 指定 UTC 偏移量而不是时区
【发布时间】:2017-10-19 16:52:11
【问题描述】:

借助 ActiveSupport::TimeWithZone,我可以执行以下操作并在正确的时区取回 TimeWithZone 对象。

Time.current.in_time_zone('Alaska')
:> Thu, 19 Oct 2017 08:45:08 AKDT -08:00

是否有与 in_time_zone 等效的方法,我可以在几秒钟内将 UTC 偏移量传递给它,并返回具有指定偏移量的 TimeWithZone 对象?

offset = -25200 # -25200 seconds == -08:00
Time.current.in_utc_offset(offset)
:> Thu, 19 Oct 2017 08:45:08 -08:00

提前致谢!

使用 Rails 5.1.2 和 Ruby 2.4.1

【问题讨论】:

    标签: ruby-on-rails ruby activesupport


    【解决方案1】:

    是的,它在原版 Ruby 中:#getlocal(sec)。它不会给你ActiveSupport::TimeWithZone,但它会给你Time,你可以用它格式化或做任何你想做的事情,包括使用ActiveSupport扩展。

    2.4.1 :016 > Time.now.getlocal(3600)
    => 2017-10-19 22:56:45 +0100 
    2.4.1 :017 > Time.now.getlocal(-3600)
    => 2017-10-19 20:56:48 -0100 
    

    PS:-25200 是以秒为单位的 7 小时 :) -8:00 将是 28800

    【讨论】:

    • 正是我想要的,谢谢。我很难在文档中找到它,但发现存在这样的东西。超级有帮助。
    猜你喜欢
    • 2018-11-01
    • 1970-01-01
    • 2010-11-19
    • 2017-05-10
    • 2014-02-04
    • 2016-09-05
    • 2018-03-01
    • 2017-10-18
    • 2017-12-19
    相关资源
    最近更新 更多