How to convert unix to NaiveDateTime?

I receive data in timestamp format (unix), for example, “1466329342388” and I need to convert it to the DateTime format that would be the NaiveDateTime in the case to insert in my bank, I only see the conversion in reverse, but not in this way , someone to help me?

1 Like

You can do the following:

iex> 1466329342 |> DateTime.from_unix!() |> DateTime.to_naive()
~N[2016-06-19 09:42:22]

note, I removed the trailing 388, the milliseconds, as the function only accepts whole seconds, you’d need to manually add that back.

Out of curiosity, why do you need it as naive date time? Given unix time is essentially %DateTime{} in UTC timezone, I’d consider keeping that representation in your app.

1 Like

This can be changed with an argument:

iex(1)> 1466329342388 |> DateTime.from_unix!(:millisecond) |> DateTime.to_naive()
~N[2016-06-19 09:42:22.388]
2 Likes

Thanks friend, it worked for me, this case I need to do the conversion because it receives this timestamp from a mobile application in my api and my update needs this according to the movement that the client does on the mobile even when offline, I need the exact time on which the action was performed. Thanks for the support.

Sadly not true :frowning:

I have to consume an API at work that sends something that looks like a Unix timestamp with the tenthousands of a second.

But it has to be devided by 10 to get it as a millisecond timestamp in the timezone of the server (Europe/Amsterdam), the modolu by 10 of that “timestamp” is a DST indicator… If it is 1 then DST is active, for 0 it is not, everything else is considered an error.

That sounds like an indictment of that API, not an indictment of Unix timestamps, right?

Of course, I just wanted to say that not everything that looks like a Unix timestamp is in UTC…

1 Like