如何在 Rails 的特定时区安排工作人员的时间?
How to schedule a worker for a time in an specific Time zone in Rails?
我有一个包含三个字段的表单:
- 日期
- 时间
- 时区
用户想为他在另一个国家的客户安排任务,也就是说,在另一个时区。所以,他会填写表格告诉:
I want this task to be executed at 12/08/2015, at 15:00 in London time zone
我有这三个参数,我不介意用户此刻在哪里或者他来自哪里。我只想将这三个字段信息转换为 UTC 日期。
如何将此字段转换为唯一的 UTC 日期?
要显式获取特定的 TimeZone
实例,请使用 ActiveSupport::TimeZone::[]
and call ActiveSupport::TimeZone#parse
在该时区内创建一个 TimeWithZone
实例:
time = ActiveSupport::TimeZone['London'].parse('12/08/2015 15:00')
#=> Wed, 12 Aug 2015 15:00:00 BST +01:00
或使用ActiveSupport::TimeZone#local
:
time = ActiveSupport::TimeZone['London'].local(2015, 8, 12, 15, 0)
#=> Wed, 12 Aug 2015 15:00:00 BST +01:00
调用 TimeWithZone#utc
returns UTC 中的 Time
实例:
time.utc
# => 2015-08-12 14:00:00 UTC
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
请注意,ActiveRecord 会自动以 UTC 格式保存 DATETIME 字段,因此通常无需将时间转换为 UTC。
接下来还有这个方法,它不依赖于ActiveSupport。
Time.zone = time_zone
time_to_utc = Time.zone.parse('time').utc
例如:
Time.zone = "London"
time_to_utc = Time.zone.parse('08/07/2015 00:00').utc
希望这能解决您的问题。
Time.use_zone('London') { Time.zone.parse('07/08/2015 17:00') }.utc
即使这对单行也能按预期工作。
ActiveSupport::TimeZone['Pacific Time (US & Canada)'].parse(params[:created_at])
我认为这会奏效。
我有一个包含三个字段的表单:
- 日期
- 时间
- 时区
用户想为他在另一个国家的客户安排任务,也就是说,在另一个时区。所以,他会填写表格告诉:
I want this task to be executed at 12/08/2015, at 15:00 in London time zone
我有这三个参数,我不介意用户此刻在哪里或者他来自哪里。我只想将这三个字段信息转换为 UTC 日期。
如何将此字段转换为唯一的 UTC 日期?
要显式获取特定的 TimeZone
实例,请使用 ActiveSupport::TimeZone::[]
and call ActiveSupport::TimeZone#parse
在该时区内创建一个 TimeWithZone
实例:
time = ActiveSupport::TimeZone['London'].parse('12/08/2015 15:00')
#=> Wed, 12 Aug 2015 15:00:00 BST +01:00
或使用ActiveSupport::TimeZone#local
:
time = ActiveSupport::TimeZone['London'].local(2015, 8, 12, 15, 0)
#=> Wed, 12 Aug 2015 15:00:00 BST +01:00
调用 TimeWithZone#utc
returns UTC 中的 Time
实例:
time.utc
# => 2015-08-12 14:00:00 UTC
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
请注意,ActiveRecord 会自动以 UTC 格式保存 DATETIME 字段,因此通常无需将时间转换为 UTC。
接下来还有这个方法,它不依赖于ActiveSupport。
Time.zone = time_zone
time_to_utc = Time.zone.parse('time').utc
例如:
Time.zone = "London"
time_to_utc = Time.zone.parse('08/07/2015 00:00').utc
希望这能解决您的问题。
Time.use_zone('London') { Time.zone.parse('07/08/2015 17:00') }.utc
即使这对单行也能按预期工作。
ActiveSupport::TimeZone['Pacific Time (US & Canada)'].parse(params[:created_at])
我认为这会奏效。