简体   繁体   English

如何在Rails的特定时区安排工作人员的时间?

[英]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. 我只想在UTC日期中转换这三个字段信息。

How can I transform this fields in an unique UTC date? 如何在唯一的UTC日期中转换此字段?

To explicitly get a specific TimeZone instance, use ActiveSupport::TimeZone::[] and call ActiveSupport::TimeZone#parse to create a TimeWithZone instance within that timezone: 要显式获取特定的TimeZone实例,请使用ActiveSupport::TimeZone::[]并调用ActiveSupport::TimeZone#parse在该时区内创建一个TimeWithZone实例:

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 : 或使用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: 调用TimeWithZone#utc以UTC返回一个Time实例:

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

ActiveSupport also provides Time::use_zone to set Time.zone inside a block: ActiveSupport还提供Time::use_zone以在块内设置Time.zone

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. 请注意,ActiveRecord会自动将DATETIME字段保存在UTC中,因此通常无需将时间转换为UTC。

Also this method next, it doesn't depend on ActiveSupport. 另外,此方法接下来也不依赖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. 我希望这能解决您的问题。

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

即使这样,单行也可以正常工作。

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

我认为这会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM