How to convert DateTime.now to UTC in Ruby?

If I have d = DateTime.now , how do I convert 'd' to UTC (with the appropriate date)?

+67
ruby
Apr 16 '09 at 11:15
source share
7 answers

d = DateTime.now.utc hit>

Unfortunately,

This seems to work in Rails, but not in vanilla Ruby (and, of course, this is the question that asks the question)

 d = Time.now.utc 

However, does it work.

Is there a reason you need to use DateTime rather than Time ? Time should include everything you need:

 irb(main):016:0> Time.now => Thu Apr 16 12:40:44 +0100 2009 
+107
Apr 16 '09 at 11:17
source share
 DateTime.now.new_offset(0) 

will work in standard Ruby (i.e. without ActiveSupport).

+145
May 15 '09 at a.m.
source share

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.

+7
Aug 03 2018-12-12T00:
source share

You can set ENV if you want your Time.now and DateTime.now respond in UTC.

 require 'date' Time.now #=> 2015-11-30 11:37:14 -0800 DateTime.now.to_s #=> "2015-11-30T11:37:25-08:00" ENV['TZ'] = 'UTC' Time.now #=> 2015-11-30 19:37:38 +0000 DateTime.now.to_s #=> "2015-11-30T19:37:36+00:00" 
+2
Nov 30 '15 at 19:40
source share

In irb:

 >>d = DateTime.now => #<DateTime: 11783702280454271/4800000000,5/12,2299161> >> "#{d.hour.to_i - d.zone.to_i}:#{d.min}:#{d.sec}" => "11:16:41" 

converts time to utc. But as indicated, if it's just Time, you can use:

 Time.now.utc 

and get it right away.

+1
Apr 16 '09 at 11:29
source share

The string representation of DateTime can be parsed by the Time class.

 > Time.parse(DateTime.now.to_s).utc => 2015-10-06 14:53:51 UTC 
+1
Oct. 06 '15 at 2:55
source share

Try this, it works in Ruby:

 DateTime.now.to_time.utc 
0
Nov 11 '16 at 2:02
source share



All Articles