1

This seems like a simple problem but I can't seem to find the answer. I have a UTC time (ie. 1323481111) and I want to change it to a DateTime or TimeWithZone object in a ruby script. I haven't found a way to do it with just ruby but I believe there should be a way to do it using ActiveSupport. It seems to me that I should be able to do it as follows:

require "active_support/all"

Time.zone.at(1323481111)

http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html

But that doesn't seem to work. Anyone know how to convert a utc int to a datetime object?

cwadding
  • 870
  • 11
  • 16

2 Answers2

2

What exactly does "doesn't seem to work" mean? Are you getting an exception like NoMethodError: undefined method 'at' for nil:NilClass? If yes, make sure you have the tzinfo gem installed and also require tzinfo. Then set a time zone and you are good to go:

>> Time.zone.at(1323481111)
NoMethodError: undefined method 'at' for nil:NilClass
[..]
>> require 'tzinfo' #=> true
>> Time.zone = "Vienna" #=> "Vienna"
>> Time.zone.at(1323481111) #=> Sat, 10 Dec 2011 02:38:31 CET 01:00
Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
  • Both great answers (@Michael Kohl and @steenslag). I wish I could check them both. But since I phrased the question using ActiveSupport this is probably the better answer. – cwadding Feb 12 '12 at 15:14
1

Without (or with) ActiveSupport:

require 'date'
DateTime.strptime("1323481111",'%s')  

If you want to set the timezone to be something else than UTC, then go by @Michael Kohl's answer.

steenslag
  • 79,051
  • 16
  • 138
  • 171