Ruby-on-rails 在 Rails 中将本地时间转换为 UTC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11833435/
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 local time to UTC in Rails
提问by Chris Stewart
In my MySQL database the updated_at field is being stored as UTC. Last week a record was entered at 7pm EDT and it's updated_at value is "2012-08-01 23:00:00". I'm trying to convert local time for a web client to UTC that can be compared against the updated_at field in the database.
在我的 MySQL 数据库中,updated_at 字段被存储为 UTC。上周美国东部时间晚上 7 点输入了一条记录,它的 updated_at 值为“2012-08-01 23:00:00”。我正在尝试将 Web 客户端的本地时间转换为可以与数据库中的 updated_at 字段进行比较的 UTC。
As an example, I'd like to convert '08/01/2012 07:00 pm' to '2012-08-01 23:00:00' (accounting for me being in EDT) but I'm missing the time zone aspect to the conversion. '7:00 pm' is local time and could be from any time zone. My current code:
例如,我想将 '08/01/2012 07:00 pm' 转换为 '2012-08-01 23:00:00'(考虑到我在 EDT)但我错过了时区方面的转换。'7:00 pm' 是当地时间,可以来自任何时区。我目前的代码:
ruby-1.9.2-head :015 > from_date = DateTime.strptime('08/01/2012 07:00 pm', '%m/%d/%Y %H:%M %p')
=> Wed, 01 Aug 2012 19:00:00 +0000
ruby-1.9.2-head :016 > from_date = Time.zone.parse(from_date.to_s).utc
=> 2012-08-01 19:00:00 UTC
Any thoughts?
有什么想法吗?
Edit: Also, I could use "%Z" in my strptime call but that's assuming I have the timezone in the value, which I currently do not. I guess I could use Javascript to send that along with the date/time value.
编辑:另外,我可以在我的 strptime 调用中使用“%Z”,但假设我在值中有时区,而我目前没有。我想我可以使用 Javascript 将它与日期/时间值一起发送。
回答by andyshi
local to utc
本地到 UTC
created_at.utc
created_at.utc
utc to local
UTC到本地
created_at.localtime
created_at.localtime
回答by Michael Durrant
First I would check your time zone setting.
首先,我会检查您的时区设置。
In your environment.rb (Rails 2) or application.rb (Rails 3) file, you can set the default timezone with: config.time_zone = 'Eastern Daylight Time (EDT)'
在您的 environment.rb (Rails 2) 或 application.rb (Rails 3) 文件中,您可以设置默认时区: config.time_zone = 'Eastern Daylight Time (EDT)'
Secondly I would look at this post for information and guidance and tips to meet your needs:
http://databasically.com/2010/10/22/what-time-is-it-or-handling-timezones-in-rails/
其次,我会查看这篇文章以获取满足您需求的信息和指导以及提示:http:
//databasically.com/2010/10/22/what-time-is-it-or-handling-timezones-in-rails/

