【问题标题】:Convert Active Support timezone original format into a string将 Active Support 时区原始格式转换为字符串
【发布时间】:2016-04-22 04:12:29
【问题描述】:

我正在尝试将 Active Support 时区原始格式转换为字符串。我想将它存储在一个字符数组中,然后单独解析每个需要的数据。

Time.zone = current_user.timezone
date_and_time = Time.zone.now

现在

date_and_time  = Thu, 21 Apr 2016 20:58:04 PDT -07:00

Ruby 方法 ( to_s ) 不会转换它。我找到了其他将其转换为的方法,但它们都只会将格式更改为数字,我希望这一天保持不变,因为我会将它存储在一个变量中,然后以不同的方法使用它。

【问题讨论】:

    标签: ruby-on-rails ruby activesupport


    【解决方案1】:

    您可以为此使用.to_formatted_s(DATE_FORMAT)

    time = Time.now                    # => Thu Jan 18 06:10:17 CST 2007
    
    time.to_formatted_s(:db)           # => "2007-01-18 06:10:17"
    time.to_formatted_s(:long)         # => "January 18, 2007 06:10"
    time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
    time.to_formatted_s(:rfc822)       # => "Thu, 18 Jan 2007 06:10:17 -0600"
    time.to_formatted_s(:iso8601)      # => "2007-01-18T06:10:17-06:00"
    

    可以在此处找到所有 DATE_FORMATS 的列表和更多信息: http://api.rubyonrails.org/classes/Time.html#method-i-to_formatted_s

    【讨论】:

      【解决方案2】:

      你可以试试这个

      date_and_time.strftime("%a %d %b %Y")
      

      你也可以检查这个guide,得到你想要的格式

      【讨论】:

      • 谢谢,这正是我想要的,它只是添加了小时和分钟,看起来很棒;)
      【解决方案3】:

      你应该得到你想要的东西:

      date_and_time.strftime("%a %d %b %Y %H:%M:%S UTC %:z")
      

      更多信息请查看strftime Docs

      说明

      硬编码 UTC 的原因是根据文档

      %z - Time zone as hour and minute offset from UTC

      所以我相信它应该一直是 UTC。

      【讨论】:

      • @PetrGazarov 我已经为此添加了解释。但是,如果您仍然认为这是一个坏主意,请您指出我的任何文档或参考资料。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      • 2013-03-20
      • 2020-01-20
      • 1970-01-01
      相关资源
      最近更新 更多