将 Active Support 时区原始格式转换为字符串
Convert Active Support timezone original format into a string
我正在尝试将 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 ) 不转换它。我找到了将其转换为的其他方法,但所有这些方法都只会将格式更改为数字,我希望日期保持不变,因为我会将其存储在一个变量中,然后以不同的方法使用它。
你可以试试这个
date_and_time.strftime("%a %d %b %Y")
你也可以检查这个guide,以获得你想要的格式
你应该用这个得到你想要的东西:
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。
您可以为此使用 .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
我正在尝试将 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 ) 不转换它。我找到了将其转换为的其他方法,但所有这些方法都只会将格式更改为数字,我希望日期保持不变,因为我会将其存储在一个变量中,然后以不同的方法使用它。
你可以试试这个
date_and_time.strftime("%a %d %b %Y")
你也可以检查这个guide,以获得你想要的格式
你应该用这个得到你想要的东西:
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。
您可以为此使用 .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