28

I'm getting this stamp from an external API:

1391655852

and I need to convert it to a Date. I have seen a lot of conversion pages on the internet and on SO, but they all seem to be going the other way. I'm not familiar with this integer format at all.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
RubyRedGrapefruit
  • 12,066
  • 16
  • 92
  • 193
  • 2
    PS: Some languages supply does date to integer conversion using milliseconds from `epoch` (while ruby uses seconds from epoch), so care needs to be taken when converting date to and from integers – bjhaid Feb 06 '14 at 04:32
  • 3
    I think it ***is*** a duplicate. You have effectively admitted that the linked post answers your question, but that it was hard to find. This is **exactly** why we have the duplicate system: Your question acts as an excellent *signpost* for the other. – Adrian Mole Dec 02 '22 at 12:38

2 Answers2

47

Use Time.at for this:

t = Time.at(i)
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
duck
  • 2,483
  • 1
  • 24
  • 34
10

I'll definitely yield to @duck's answer - in my opinion, that's the best way to convert an integer to Time - but if you're explicitly looking for a Date, you'll want to do a bit more work:

require 'date'

t = Time.at(i)
date = t.to_date

In the above example, date will be of class Date.

CDub
  • 13,146
  • 4
  • 51
  • 68