Current Unix Timestamp SECONDS SINCE JAN 01 1970

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

How to convert Datetime to Unix timestamp in Elixir

🎈 🎈 🎈
+1

    # Convert DateTime to Unix timestamp
    date_time = DateTime.utc_now() |> DateTime.from_naive!("Etc/UTC")
    date_time = DateTime.new!(~U[2022-05-15 08:12:43Z])
    unix_timestamp = DateTime.to_unix(date_time)
    
    IO.puts("Unix Timestamp: #{unix_timestamp}")            
        

Output:
Unix Timestamp: 1652602363
Example only. There may be multiple ways to perform this operation.

Code Explanation

In this Elixir example, we first create a DateTime object for '2022-05-15 08:12:43' UTC using DateTime.new!(~U[...]) syntax.
The DateTime.to_unix() function is then used to convert the DateTime object into a Unix timestamp.
The result is the Unix timestamp '1652602363', which is printed. This method simplifies converting human-readable date-time values into Unix timestamps.



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