Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何将日期转换为具有特定时区的ActiveSupport::TimeWithZone?_Ruby_Timezone_Activesupport - Fatal编程技术网

Ruby 如何将日期转换为具有特定时区的ActiveSupport::TimeWithZone?

Ruby 如何将日期转换为具有特定时区的ActiveSupport::TimeWithZone?,ruby,timezone,activesupport,Ruby,Timezone,Activesupport,我有一个日期对象,如下所示: >> the_date => Tue, 12 Jun 2012 >> the_date.class => Date 以及存储为字符串的时区: >> tz = "Pacific Time (US & Canada)" => "Pacific Time (US & Canada)" 我希望在给定时区中的给定日期的午夜生成ActiveSupport::TimeWithZone(而不是utc中给定日

我有一个日期对象,如下所示:

>> the_date
=> Tue, 12 Jun 2012

>> the_date.class
=> Date
以及存储为字符串的时区:

>> tz = "Pacific Time (US & Canada)"
=> "Pacific Time (US & Canada)"
我希望在给定时区中的给定日期的午夜生成ActiveSupport::TimeWithZone(而不是utc中给定日期的午夜,然后转换为给定时区)。到目前为止,我发现最好的方法是非常丑陋的:

>> the_time = ActiveSupport::TimeZone.new(tz).parse(the_date.to_s)
=> Tue, 12 Jun 2012 00:00:00 PDT -07:00

>> the_time.class
=> ActiveSupport::TimeWithZone

一定有更好的方法来生成这个!有人知道如何做到这一点吗?

其实不是更好,但与您的解决方案不同:

the_date.to_time.in_time_zone
#=> Mon, 11 Jun 2012 22:00:00 UTC +00:00

the_date.to_time.in_time_zone(tz)
#=> Mon, 11 Jun 2012 15:00:00 PDT -07:00

Time.zone = tz
#=> "Pacific Time (US & Canada)"

the_date.to_time.in_time_zone
#=> Mon, 11 Jun 2012 15:00:00 PDT -07:00

the_date.to_time.in_time_zone.end_of_day
#=> Mon, 11 Jun 2012 23:59:59 PDT -07:00

(the_date.to_time.in_time_zone + 1.day).beginning_of_day
#=> Tue, 12 Jun 2012 00:00:00 PDT -07:00