Jacka
Jacka

Reputation: 2560

Convert string to datetime in specific timezone

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)

Upvotes: 5

Views: 8779

Answers (2)

pdobb
pdobb

Reputation: 18037

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])

Upvotes: 10

Shamsul Haque
Shamsul Haque

Reputation: 2451

Try this:-

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

Rails console output:-

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

Upvotes: -1

Related Questions