tags:

views:

2093

answers:

3

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

+5  A: 

d = DateTime.now.utc

Oops!

That seems to work in Rails, but not vanilla Ruby (and of course that is what the question is asking)

d = Time.now.utc

Does work however.

Is there any reason you need to use DateTime and not Time? Time should include everything you need:

irb(main):016:0> Time.now
=> Thu Apr 16 12:40:44 +0100 2009
DanSingerman
Because I want the correct date for the conversion, ie, for GMT +10 can be ahead the next day...
Ash
Time will do that for you just fine. Time includes the date part as well, not just the time of the day. Do Time.now.inspect to take a look.
DanSingerman
Oh sweet. So whats the difference between Date, Time and DateTime then?
Ash
Time is stored internally as the number of seconds and microseconds since the epoch, January 1, 1970 00:00 UTC. Date, internally, is represented as an Astronomical Julian Day Number, and DateTime is just plain weird (which is probably why Rails overrides it)
DanSingerman
Ok awesome, thanks, this is perfect. :)
Ash
+1  A: 

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"

will convert the time to the utc. But as posted if it is just Time you can use:

Time.now.utc

and get it straight away.

railsninja
+1  A: 
DateTime.now.new_offset(0)

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

Greg Campbell