Fran Martinez
Fran Martinez

Reputation: 3052

How to schedule a worker for a time in an specific Time zone in Rails?

I have a form with three fields:

  1. Date
  2. Time
  3. Time zone

Users would like to schedule a task for his customers in another country, that means, in another time zone. So, he will fill the form telling:

I want this task to be executed at 12/08/2015, at 15:00 in London time zone

I have these three params and I don't mind where the user is at this moment or where is he from. I just want to transform this three fields information in an UTC date.

How can I transform this fields in an unique UTC date?

Upvotes: 2

Views: 890

Answers (4)

Santanu
Santanu

Reputation: 960

ActiveSupport::TimeZone['Pacific Time (US & Canada)'].parse(params[:created_at])

this will work, I think.

Upvotes: 0

Kishore Mohan
Kishore Mohan

Reputation: 1060

Time.use_zone('London') { Time.zone.parse('07/08/2015 17:00') }.utc

Even this works as expected with single line.

Upvotes: 1

Stefan
Stefan

Reputation: 114188

To explicitly get a specific TimeZone instance, use ActiveSupport::TimeZone::[] and call ActiveSupport::TimeZone#parse to create a TimeWithZone instance within that timezone:

time = ActiveSupport::TimeZone['London'].parse('12/08/2015 15:00')
#=> Wed, 12 Aug 2015 15:00:00 BST +01:00

or using ActiveSupport::TimeZone#local:

time = ActiveSupport::TimeZone['London'].local(2015, 8, 12, 15, 0)
#=> Wed, 12 Aug 2015 15:00:00 BST +01:00

Calling TimeWithZone#utc returns a Time instance in UTC:

time.utc
# => 2015-08-12 14:00:00 UTC

ActiveSupport also provides Time::use_zone to set Time.zone inside a block:

Time.use_zone('London') { Time.zone.parse('12/08/2015 15:00') }
#=> Wed, 12 Aug 2015 15:00:00 BST +01:00

Note that ActiveRecord automatically saves DATETIME fields in UTC, so there's usually no need to convert the time to UTC.

Upvotes: 3

adriagalin
adriagalin

Reputation: 21

Also this method next, it doesn't depend on ActiveSupport.

Time.zone = time_zone
time_to_utc = Time.zone.parse('time').utc

for example:

Time.zone = "London"
time_to_utc = Time.zone.parse('08/07/2015 00:00').utc

I hope this solves your problem.

Upvotes: 2

Related Questions