converting Date object to TimeWithZone

后端 未结 5 737
清歌不尽
清歌不尽 2020-12-31 18:24

I need to convert a Date object into a TimeWithZone object representing the beginning of that day in a given time zone.

The following approach works, but seems too c

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-31 19:01

    If you have Time.zone set in Rails then you can call Date#at_beginning_of_day (see http://api.rubyonrails.org/classes/Date.html#method-i-at_beginning_of_day). Contrast this with Date#to_datetime:

    Time.zone
     => #, @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
    

提交回复
热议问题