If I have d = DateTime.now
, how do I convert 'd' into UTC (with the appropriate date)?
views:
2093answers:
3
+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
2009-04-16 11:17:49
Because I want the correct date for the conversion, ie, for GMT +10 can be ahead the next day...
Ash
2009-04-16 11:29:41
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
2009-04-16 11:32:31
Oh sweet. So whats the difference between Date, Time and DateTime then?
Ash
2009-04-16 11:40:41
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
2009-04-16 11:44:56
Ok awesome, thanks, this is perfect. :)
Ash
2009-04-16 11:57:22
+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
2009-04-16 11:29:04
+1
A:
DateTime.now.new_offset(0)
will work in standard Ruby (i.e. without ActiveSupport).
Greg Campbell
2009-05-15 00:14:59