在 Rails 中将 DateTime 字符串转换为 UTC [英] Convert DateTime String to UTC in rails
问题描述
我有一个这样的字符串:
I have a string like this:
"2010-01-01 12:30:00"
我需要将其从当前本地时区转换为 UTC.
I need that to convert to UTC from the current local time zone.
我试过这个,但它似乎认为字符串已经是UTC了.
I tried this, but it seems to think that the string is already UTC.
"2010-01-01 12:30:00".to_datetime.in_time_zone("Central Time (US & Canada)")
=> Fri, 01 Jan 2010 06:30:00 CST -06:00
我不知道从哪里开始.
从我的评论中添加了这个:
added this from my comment:
>> Time.zone = "Pacific Time (US & Canada)"
=> "Pacific Time (US & Canada)"
>> Time.parse("2010-10-27 00:00:00").getutc
=> Wed Oct 27 06:00:00 UTC 2010
>> Time.zone = "Mountain Time (US & Canada)"
=> "Mountain Time (US & Canada)"
>> Time.parse("2010-10-27 00:00:00").getutc
=> Wed Oct 27 06:00:00 UTC 2010
感谢您的帮助.
推荐答案
Time.parse("2010-01-01 12:30:00").getutc
编辑
(咬牙切齿地想着 Ruby/Rails 日期/时间处理的噩梦)
(grinding teeth while thinking about the nightmare which is Ruby/Rails date/time handling)
好的,这个怎么样:
Time.zone.parse("2010-01-01 12:30:00").utc
注意 Time.zone.parse
返回一个 DateTime
,而附加 .utc
给你一个 Time
>.有差异,所以要小心.
Note that Time.zone.parse
returns a DateTime
, while appending the .utc
gives you a Time
. There are differences, so beware.
此外,Time.zone 是 Rails (ActiveSupport) 的一部分,而不是 Ruby.只是让你知道.
Also, Time.zone is part of Rails (ActiveSupport), not Ruby. Just so you know.
这篇关于在 Rails 中将 DateTime 字符串转换为 UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!