2

我正在使用 datetimepicker 并且需要将从 params 获得的字符串 datetime 保存到特定的、与用户相关的时区中的 datetime。它将允许我将正确的 UTC 日期时间保存到数据库。

params[:notify_at] #=> "2014-07-05 14:30:00"

user.time_zone #=> #<ActiveSupport::TimeZone:0x00000007535ac8 @name="Warsaw", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Europe/Warsaw>, @current_period=nil>

我想做类似的事情:

date = params[:notify_at].to_datetime(user.time_zone) #=> Sat, 05 Jul 2014 12:30:00 +0000
(its 14:30 in user's localtime but 12:30 in UTC)
4

2 回答 2

7

您可以使用in_time_zone方法。例如:

DateTime.current.in_time_zone("Alaska")
# => Fri, 23 May 2014 07:21:30 AKDT -08:00

因此,对于您的用例:

params[:notify_at].to_datetime.in_time_zone(user.time_zone)

专业提示:如果使用 Rails v4+,您实际上可以直接在字符串上执行此操作:

"2014-07-05 14:30:00".in_time_zone("Alaska")
# => Sat, 05 Jul 2014 14:30:00 AKDT -08:00

更新

您可以将字符串直接解析到时区(字符串应该已经在该时区中),如下所示:

Time.zone.parse("2014-07-05 14:30:00")
# => Sat, 05 Jul 2014 14:30:00 CEST +02:00

因此,对于您的用例,请执行以下操作:

user.time_zone.parse(params[:notify_at])
于 2014-05-23T15:22:54.927 回答
-1

尝试这个:-

date = params[:notify_at].to_datetime.in_time_zone(user.time_zone)

Rails 控制台输出:-

1.9.3p385 :004 > d= "2014-07-05 14:30:00"
=> "2014-07-05 14:30:00" 
1.9.3p385 :010 > d.to_datetime.in_time_zone("Pacific Time (US & Canada)")
=> Sat, 05 Jul 2014 07:30:00 PDT -07:00 
1.9.3p385 :011 > d.to_datetime.in_time_zone("Alaska")
=> Sat, 05 Jul 2014 06:30:00 AKDT -08:00 
1.9.3p385 :012 > to_datetime.in_time_zone
于 2014-05-23T15:27:15.903 回答