Rails - 时区转换 [英] Rails - time zone conversion

查看:32
本文介绍了Rails - 时区转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将带有外部时区字段的日期时间转换为 UTC.有人可以向我解释为什么这不起作用吗?

I'm trying to convert a datetime with an external timezone field into UTC. Can someone explain to me why this doesn't work?

time_str = '2016-03-01 00:00'
zone_str = 'Pacific Time (US & Canada)'

Time.use_zone(zone_str) { Time.parse(time_str).in_time_zone('UTC') }

我的期待:

'2016-03-01 08:00'

我得到了什么:

'2016-03-01 06:00'

基本上,它忽略了我的 use_zone 调用而只使用我的本地时区,即中央时区.

Basically, it's ignoring my use_zone call and just using my local time zone, which is Central.

我应该怎么做?

-- 编辑 --

请注意,我并不是要在整个应用程序中设置时区.我只是尝试采用一组输入(时间和时区在单独的表单字段中)并将它们转换为 UTC.

Note that I am NOT trying to set the time zone across the entire application. I am ONLY trying to take a single set of inputs (time and time zone in separate form fields) and convert those to UTC.

推荐答案

试试这个解决方案:

 time = ActiveSupport::TimeZone.new(zone_str).parse(time_str)
 time.in_time_zone('UTC')
 #=> Tue, 01 Mar 2016 08:00:00 UTC +00:00

这篇关于Rails - 时区转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆