converting Date object to TimeWithZone

后端 未结 5 706
清歌不尽
清歌不尽 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:23

    I'm late to the party, but this is still a great question. ActiveSupport's in_time_zone was introduced since the O.P., but it does exactly what you want without parsing a string (slow) or setting Time.zone (risky):

    >> 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
    

    Of course if you want the beginning of day expressed at utc, you can do this:

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

提交回复
热议问题