Converting a Date Object to TimeWithZone

I need to convert a Date object to a TimeWithZone object representing the start of this day in a given time zone.

The following approach works, but seems too confusing as it requires me to convert the date to a string:

?> date = Date.parse("2010-02-17")
=> Wed, 17 Feb 2010
>> ActiveSupport::TimeZone['Eastern Time (US & Canada)'].parse(date.to_s)
=> Wed, 17 Feb 2010 00:00:00 EST -05:00
>> ActiveSupport::TimeZone['UTC'].parse(date.to_s)
=> Wed, 17 Feb 2010 00:00:00 UTC 00:00

Is there a better way that I am missing?

Edit: People offer options:

?> date.to_datetime.in_time_zone('Eastern Time (US & Canada)').beginning_of_day
=> Tue, 16 Feb 2010 00:00:00 EST -05:00

As you can see, this is not an equivalent conversion, since it leaves me at the beginning of February 16 EST instead of the beginning of February 17 EST.

+6
source share
5 answers

, . ActiveSupport in_time_zone O.P., , , () Time.zone():

>> date = Date.parse("2010-02-17")
=> Wed, 17 Feb 2010
>> date.in_time_zone('Eastern Time (US & Canada)')
=> Wed, 17 Feb 2010 00:00:00 EST -05:00

, , utc, :

>> date.in_time_zone('Eastern Time (US & Canada)').utc
=> 2010-02-17 05:00:00 UTC
+6

Time.zone Rails, Date#at_beginning_of_day (. http://api.rubyonrails.org/classes/Date.html#method-i-at_beginning_of_day). Date#to_datetime:

Time.zone
 => #<ActiveSupport::TimeZone:0x10cf10858 @tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, @utc_offset=nil, @current_period=nil, @name="UTC"> 

date = Date.today
 => Thu, 31 May 2012 

date.to_datetime
 => Thu, 31 May 2012 00:00:00 +0000 

date.at_beginning_of_day
 => Thu, 31 May 2012 00:00:00 UTC +00:00 

Time.zone = 'America/Chicago'
 => "America/Chicago" 

date.to_datetime
 => Thu, 31 May 2012 00:00:00 +0000 

date.at_beginning_of_day
 => Thu, 31 May 2012 00:00:00 CDT -05:00
+4

, - to_datetime to_time, in_time_zone , , . , , UTC. , .

TimeZone, .

, TimeWithZone :

time = zone.local(date.year, date.month, date.day)

, , , ​​ 4-, 5- 6- #local.

zone (Time.zone), ActiveSupport :

time = date.to_time_in_current_zone

. , , UTC , , DST, , DST:

irb(main):009:0> zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
=> (GMT-05:00) Eastern Time (US & Canada)
irb(main):010:0> t1 = zone.local(2013, 1, 1)
=> Tue, 01 Jan 2013 00:00:00 EST -05:00
irb(main):011:0> t2 = zone.local(2013, 5, 1)
=> Wed, 01 May 2013 00:00:00 EDT -04:00
irb(main):012:0> t1.utc_offset
=> -18000
irb(main):013:0> t2.utc_offset
=> -14400
+2

- ?

'2010-04-01'.to_time.in_time_zone('Eastern Time (US & Canada)').beginning_of_day
0

utc_offset:

d = Date.today
Time.zone.class.all.map(&:name).map { |tz| dt = d.to_datetime.in_time_zone(tz); dt -= dt.utc_offset }

ActiveSupport:: TimeZone [tz] .

Time.zone.class.all.map(&:name).map { |tz| o = d.to_datetime.in_time_zone(tz).utc_offset - ActiveSupport::TimeZone[tz].utc_offset }
0

All Articles