Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-08-20
Convert Unix Timestamp to Datetime in Elixir

How to convert Unix timestamp to Datetime in Elixir

🎈 🎈 🎈
+1

    # Convert Unix timestamp to DateTime
    unix_timestamp = 1232242987
    {:ok, date_time} = DateTime.from_unix(unix_timestamp)
    
    IO.puts("Converted Date: #{date_time}")            
        

Output:
Converted Date: 2009-01-18 01:43:07
Example only. There may be multiple ways to perform this operation.

Code Explanation

In this Elixir timestamp conversion example , the Unix timestamp '1232242987' is passed to the DateTime.from_unix() function, which converts it into a DateTime object representing the date and time in UTC (2009-01-18 01:43:07).
The result is a tuple where the first element is :ok to indicate success, and the second element is the DateTime object. The DateTime object is then printed in a human-readable format.



Other useful Elixir date functions

Function Description Example
DateTime.utc_now() Returns the current UTC date and time as a DateTime object. DateTime.utc_now() returns 2024-08-28 16:34:56Z
DateTime.from_unix() Converts a Unix timestamp (in seconds or milliseconds) to a DateTime object. DateTime.from_unix(1652602245) returns 2022-05-15 08:10:45Z
DateTime.to_unix() Converts a DateTime object to a Unix timestamp in seconds or milliseconds. DateTime.to_unix(date_time) returns 1652602245
NaiveDateTime.new() Creates a NaiveDateTime object from specified values (year, month, day, hour, minute, second). NaiveDateTime.new(2022, 5, 15, 8, 30, 45) returns 2022-05-15 08:10:45
Date.new() Creates a Date object for a specific date (year, month, day). Date.new(2022, 5, 15) returns 2022-05-15
Date.add() Adds a number of days to a Date object. Date.add(Date.utc_today(), 5) adds 5 days to the current date.
Date.diff() Returns the number of days between two Date objects. Date.diff(Date.utc_today(), Date.new(2022, 5, 15)) returns the difference in days.
DateTime.add() Adds a number of seconds to a DateTime object. DateTime.add(date_time, 3600) adds 1 hour to the date.
DateTime.compare() Compares two DateTime objects. DateTime.compare(date_time1, date_time2) returns :lt, :eq, :gt (less than, equal, greater than).
Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-08-20
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder