Ruby-on-rails 在 Rails 中将 DateTime 字符串转换为 UTC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4046289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert DateTime String to UTC in rails
提问by Toby Joiner
I have a string like this:
我有一个这样的字符串:
"2010-01-01 12:30:00"
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.
我试过这个,但似乎认为该字符串已经是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
I am not sure where to go from here.
我不知道从这里去哪里。
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
Thanks for any help.
谢谢你的帮助。
回答by zetetic
Time.parse("2010-01-01 12:30:00").getutc
EDIT
编辑
(grinding teeth while thinking about the nightmare which is Ruby/Rails date/time handling)
(一边磨牙一边想着 Ruby/Rails 日期/时间处理的噩梦)
OK, how about this:
好的,这个怎么样:
Time.zone.parse("2010-01-01 12:30:00").utc
Note that Time.zone.parsereturns a DateTime, while appending the .utcgives you a Time. There are differences, so beware.
请注意,Time.zone.parse返回 a DateTime,同时附加.utc给您 a Time。有差异,所以要小心。
Also, Time.zone is part of Rails (ActiveSupport), not Ruby. Just so you know.
此外,Time.zone 是 Rails (ActiveSupport) 的一部分,而不是 Ruby。只要你知道。
回答by Deepak Mahakale
In Rails 4 and aboveyou can directly use in_time_zone
在Rails 4 及更高版本中,您可以直接使用in_time_zone
"2010-01-01 12:30:00".in_time_zone
#=> Fri, 01 Jan 2010 12:30:00 EST -05:00
"2010-01-01 12:30:00".in_time_zone.utc
#=> 2010-01-01 17:30:00 UTC
回答by d.danailov
For APIs you can use:
对于 API,您可以使用:
utc_date = Time.parse("2013-05-31 00:00").utc.iso8601 #=> Result will be: 2013-05-30T21:00:00Z
You can check these articles:
您可以查看这些文章:

