Rails:如何将日期时间字符串解析为特定时区 [英] Rails: How to parse date-time string into a specific time zone

查看:121
本文介绍了Rails:如何将日期时间字符串解析为特定时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Debian上使用了Rails 3.2和ruby 1.9.3。我有一个通过HTML表单以字符串形式收集日期,时间和时区的应用程序。这样的:

  start_date:04-15-2010,
start_time:10:00:00 ,
时区:中部时间(美国和加拿大)

d喜欢做的是将这3个元素解析成一个单一的日期,它被保存到我的数据库中作为UTC,在这种情况下,它会添加7个小时到开始时间,一旦它在UTC时区。
所以存储的时间将是17:00,一旦它在数据块中作为UTC而不是收到的中央时间。



我已经尝试过这样的东西来解析日期:

  ActiveSupport :: TimeZone [timezone] .at DateTime.strptime({2012-04-09 20:00 :00},{%Y-%m-%d%H:%M:%S})to_i 

但是,我无法将时区与%Z结合在一起。它不解析或时间被解释为UTC而不是中央时间。所以我的问题是,如何将日期字符串强制转换成某个时区,而不会更改存储的实际日期/时间的值。我希望能够将该字符串解析成日期/时间对象,该对象包含当时的正确时区,以便将来的时区转换是准确的。我已经看了一遍,找不到办法。这很奇怪,因为这看起来像HTML表单中输入的日期一样。感谢您的帮助。

解决方案

%Z 是正确的方式指定时区名称。你试过以下吗?

  date_and_time ='%m-%d-%Y%H:%M:%S% Z'
DateTime.strptime(04-15-2010 10:00:00 Central Time(US& Canada),date_and_time)


I'm using Rails 3.2 and ruby 1.9.3 on Debian. I have an app that collects a date, time, and timezone in the form of strings via an HTML form. Something like this:

start_date: "04-15-2010",
start_time: "10:00:00",
timezone: "Central Time (US & Canada)"

What I'd like to do is parse these 3 elements into a single date that is saved into my database as UTC, which in this case would add 7 hours to the start time, once it's in the UTC time zone. So the stored time would be 17:00 once it's in the DB as UTC instead of the received Central time.

I have tried something like this to parse the date:

ActiveSupport::TimeZone[timezone].at DateTime.strptime("{ 2012-04-09 20:00:00 }", "{ %Y-%m-%d %H:%M:%S }").to_i

However, I'm not able to incorporate the time zone into the resulting time with %Z. It either doesn't parse or the time is interpreted as UTC not Central time. So my question is, how to coerce a date string into a certain time zone without changing the value of the actual date/time stored. I'd like to be able to parse the string into a date/time object that includes the correct time zone with it at that time so that future time zone conversions are accurate. I've looked all over and can't find a way to do this. It's strange, since this seems like something common one does with dates inputted from HTML forms. Thank you for any help.

解决方案

%Z is the correct way to specify a Time zone name. Have you tried the following ?

date_and_time = '%m-%d-%Y %H:%M:%S %Z'
DateTime.strptime("04-15-2010 10:00:00 Central Time (US & Canada)",date_and_time)

这篇关于Rails:如何将日期时间字符串解析为特定时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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