Friday, April 29, 2011

How do I Convert DateTime.now to UTC in Ruby?

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

From stackoverflow
  • 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
    
    Ash : Because I want the correct date for the conversion, ie, for GMT +10 can be ahead the next day...
    DanSingerman : 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.
    Ash : Oh sweet. So whats the difference between Date, Time and DateTime then?
    DanSingerman : 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)
    Ash : Ok awesome, thanks, this is perfect. :)
  • 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.

  • DateTime.now.new_offset(0)
    

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

0 comments:

Post a Comment