Nic*_*las 20 ruby timezone ruby-on-rails datetimeoffset strptime
我有一个我解析的字符串DateTime.strptime.字符串中Date的时区是CET,但Ruby创建了一个UTC DateTime对象,当然它的偏移量为2小时.
目前我正在解决这个问题,DateTime.strptime().change(:offset => "+0020")但我很确定这不是它的工作方式.
有人可以用正确的方法来启发我吗?
War*_*Hog 12
我用以下方式使用它:
ruby-1.9.2-head :001 > require 'date'
=> true
ruby-1.9.2-head :002 > fmt = "%m-%d-%Y %H:%M:%S %Z"
=> "%m-%d-%Y %H:%M:%S %Z"
ruby-1.9.2-head :003 > DateTime.strptime "10-26-2011 10:16:29 CET", fmt
=> #<DateTime: 2011-10-26T10:16:29+01:00 (212186380589/86400,1/24,2299161)>
ruby-1.9.2-head :004 > DateTime.strptime "10-26-2011 10:16:29 UTC", fmt
=> #<DateTime: 2011-10-26T10:16:29+00:00 (212186384189/86400,0/1,2299161)>
ruby-1.9.2-head :005 > DateTime.strptime "10-26-2011 10:16:29 PST", fmt
=> #<DateTime: 2011-10-26T10:16:29-08:00 (212186412989/86400,-1/3,2299161)>
Run Code Online (Sandbox Code Playgroud)
这是你的意思吗?
至少从 Rails 4.2 开始(可能更早,还没有测试过),只要您使用Time#strptime而不是DateTime.strptime,就会自动应用当前时区:
> DateTime.strptime('12/28/2016 5:00 PM', '%m/%d/%Y %H:%M %p')
=> Wed, 28 Dec 2016 17:00:00 +0000
> Time.strptime('12/28/2016 5:00 PM', '%m/%d/%Y %H:%M %p')
=> 2016-12-28 17:00:00 -0800
Run Code Online (Sandbox Code Playgroud)
小智 5
这适用于Rails 5:
Time.zone.strptime("2017-05-20 18:20:10", "%Y-%m-%d %H:%M:%S")
Run Code Online (Sandbox Code Playgroud)
返回指定时区的时间。
Abd*_*bdo -3
我无法删除已接受的答案
正如@LeeJarvis 在下面的评论部分指出的那样,Chronic.parse不接受:time_class选项。所以这个答案是有问题的,虽然它看起来有效,但事实并非如此(除非 Chronic 允许:time_class很快通过一个选项。)
慢性宝石确实很强大。
我这样使用它:
Chronic.parse("next 5:00 pm",
:time_class => ActiveSupport::TimeZone.new(User.first.time_zone)).utc
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,User.first.time_zone是“太平洋时间(美国和加拿大)”。
Chronic 支持多种格式,请访问 https://github.com/mojombo/chronic查看
确保传递:time_class选项并转换为 UTC(在文档中,Chronic:time_class在调用解析之前设置。我避免使用这种方法,因为它可能会导致应用程序中的其他部分无法工作)
TimeZone 的文档位于 http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html
| 归档时间: |
|
| 查看次数: |
16766 次 |
| 最近记录: |