Creating a DateTime from UTC seconds

ruby, ruby-on-rails-3

Solution

You can use the Time class for this, i.e.

t = Time.at(1344899588)

If you need a Date object rather than a Time object, you can do:

d = Time.at(1344899588).to_date

And, if you need a DateTime object, you can do:

dt = Time.at(1344899588).to_datetime

Which, btw, yields `Mon, 13 Aug 2012 16:13:08 -0700`

Problem

I can't believe that I can't find this anywhere, but how can you create a DateTime from UTC seconds? Similar to how in Java you can do `Calendar.getInstance().setTimeInMillis(time)` to get a certain time. `DateTime.new 1344899588` didn't work, and I don't see anything in the DateTime API docs that shows how to do this. This works, but seems like a roundabout way to do it: ``` DateTime.strptime(1344899588.to_s, "%s") ```

Original source