Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-08-21
Convert Datetime to Unix Timestamp in Crystal

How to convert Datetime to Unix timestamp in Crystal

🎈 🎈 🎈
+1

    # Convert date to Unix timestamp
    date_time = Time.new(2023, 08, 24, 00, 00, 00, Time::Location::UTC)
    unix_timestamp = date_time.to_unix
    
    puts "Unix Timestamp: #{unix_timestamp}"
        

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

Code Explanation

In this Crystal example, we create a Time object representing the date '2022-05-15 08:10:45' in UTC. The #to_unix method is then called on the Time object to convert it into a Unix timestamp, which is the number of seconds since January 1, 1970.
The result is the Unix timestamp '1652602245', which matches the original date. This method is simple and direct for converting dates to Unix timestamps in Crystal.



Other useful Crystal date functions

Function Description Example
Time.now Returns the current date and time based on the system's time zone. Time.now returns 2024-08-28 12:34:56
Time.unix() Creates a Time object from a Unix timestamp (seconds since January 1, 1970). Time.unix(1652602245) returns 2022-05-15 08:10:45 UTC
Time.new() Creates a Time object from specified year, month, day, hour, minute, and second. Time.new(2022, 5, 15, 8, 30, 45, Time::Location::UTC) returns 2022-05-15 08:10:45 UTC
#to_unix Returns the Unix timestamp (seconds since January 1, 1970) for the Time object. date_time.to_unix returns 1652602245
Time.parse() Parses a string into a Time object based on the provided format. Time.parse("2022-05-15 08:10:45", "%Y-%m-%d %H:%M:%S") returns 2022-05-15 08:10:45 UTC
Time.format() Formats a Time object as a string according to the provided format. date_time.format("%Y-%m-%d %H:%M:%S") returns 2022-05-15 08:10:45
Time.utc_now Returns the current UTC date and time. Time.utc_now returns 2024-08-28 16:34:56 UTC
Time::Span Represents a time span (duration), which can be added or subtracted from Time objects. time_span = Time::Span.new(5.days) creates a time span of 5 days.
Current Unix Timestamp SECONDS SINCE JAN 01 1970

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