Convert string to datetime in specific timezone

datetime, ruby, ruby-on-rails, time, zone

Solution

You can use the in_time_zone method. For example:

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

So for your use case:

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

Pro Tip: If using Rails v4+ you can actually do this directly on the string:

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

UPDATE

You can parse a string directly into a time zone (where the String should already be IN that time zone) like this:

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

So for your use case do:

user.time_zone.parse(params[:notify_at])

Problem

I'm using datetimepicker and need to save the string datetime obtained from params to a datetime in a specific, user dependent time zone. It will allow me to save proper UTC datetime to database. ``` 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> ``` And I would like to do something like: ``` 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) ```

Original source