you786
you786

Reputation: 3540

Creating a DateTime from UTC seconds

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")

Upvotes: 4

Views: 377

Answers (1)

ipd
ipd

Reputation: 5714

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

Upvotes: 5

Related Questions