Unfortunately, the DateTime class does not have the convenience methods available in the Time class for this. You can convert any DateTime object to UTC as follows:
d = DateTime.now d.new_offset(Rational(0, 24))
You can switch from UTC to localtime using:
d.new_offset(DateTime.now.offset)
where d is a DateTime object in UTC. If you want these methods to be convenient, you can create them as follows:
class DateTime def localtime new_offset(DateTime.now.offset) end def utc new_offset(Rational(0, 24)) end end
You can see this in action in the following irb session:
d = DateTime.now.new_offset(Rational(-4, 24)) => #<DateTime: 106105391484260677/43200000000,-1/6,2299161> 1.8.7 :185 > d.to_s => "2012-08-03T15:42:48-04:00" 1.8.7 :186 > d.localtime.to_s => "2012-08-03T12:42:48-07:00" 1.8.7 :187 > d.utc.to_s => "2012-08-03T19:42:48+00:00"
As you can see above, the original DateTime object has an offset of -04: 00 (Eastern Time). I am in Pacific Time with an offset of -07: 00. Calling localtime , as described earlier, correctly converts the DateTime object to local time. Calling utc on an object correctly converts it to a UTC offset.
Joel Watson Aug 03 2018-12-12T00: 00Z
source share