21

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.


WHY THIS IS NOT A DUPLICATE QUESTION *

This question should not be marked as a duplicate because the referenced question specifically mentions seconds since epoch. While that is actually the number I was looking for, I had no idea it was called that. Judging by the very quick up-votes and a favorite as well as 40 views in less than one week, I would judge that the seconds since epoch time format is not universally known among programmers. Thus SO users will benefit from the question being asked both ways.

AKWF
  • 12,126
  • 14
  • 88
  • 189
  • 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

2 Answers2

38

Use Time.at for this:

t = Time.at(i)
the Tin Man
  • 155,156
  • 41
  • 207
  • 295
duck
  • 2,318
  • 1
  • 20
  • 32
7

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
  • 12,860
  • 4
  • 50
  • 66