5

I've been using this answer to convert epoch time to DateTime. I have this epoch number:

epoch = 1549626705942

and do:

Time.at(epoch).to_datetime

However, I get this as the result:

#<DateTime: 51075-09-19T08:45:42+02:00 ((20376082j,24342s,0n),+7200s,2299161j)>

I'm using Ruby version 2.5.3p105 and my clock is set to the current year. This epoch value evaluates to today's date (February 2nd, 2019) yet I get a year 51075. Really not sure what's going on.

It's also weird because, when I enter my timestamp at a site like this one I get today's date but here I get the same result as my Ruby code.

Edit: I tried to remove the last 3 numbers of this date and got a correct date. So is it that there are 2 epoch "formats" so to say?

anemaria20
  • 1,646
  • 2
  • 17
  • 36

1 Answers1

8

You are passing miliseconds to the Time::at() method. You should pass seconds there. Link to docs is here.

To retrieve Epoch value(in seconds), use Time#to_i

UPD

This will work for you:

Time.at(0, your_epoch_milliseconds, :millisecond)
intale
  • 831
  • 5
  • 7
  • Is there a way to also pass milliseconds and get the correct datetime? – anemaria20 Feb 08 '19 at 12:23
  • And how do you retrive miliseconds? – intale Feb 08 '19 at 12:25
  • I retrieved the epoch API with milliseconds from an API. So I can either trim this integer (will trimming the last 3 numbers always work?) or configure Ruby so it correctly converts that number into DateTime with the current format. I'm not interested in retrieving but converting an epoch value already given to me. – anemaria20 Feb 08 '19 at 12:31
  • Thanks, can you reference the resource where you got/figured this solution? I'm looking at ".at" rdoc and can't find any reference to this. – anemaria20 Feb 08 '19 at 12:45
  • I gave you the reference in the answer. Here is copy-paste http://ruby-doc.org/core-2.5.3/Time.html#method-c-at – intale Feb 08 '19 at 12:46
  • Was wondering how is it different than this https://stackoverflow.com/a/39929299/4214184 – anemaria20 Feb 08 '19 at 12:46
  • Well, you can, of course, devide your milliseconds value by 1000.0. But there is already built-in feature in ruby to rich desired result. Take a look closer on description of `Time::at` method, this line - `at(seconds, milliseconds, :millisecond)` – intale Feb 08 '19 at 12:49