Current Unix Timestamp SECONDS SINCE JAN 01 1970

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

How to convert Unix timestamp to Datetime in Crystal

🎈 🎈 🎈
+1

    # Convert Unix timestamp to date
    unix_timestamp = 1652602245
    date_time = Time.unix(unix_timestamp)
    
    puts "Converted Date: #{date_time}"
        

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

Code Explanation

Converting a unix timestamp to date can be achieved in Crystal using the Time.unix(unix_timestamp) function to convert the Unix timestamp '1652602245' into a Time object.
The result is a date and time corresponding to '2022-05-15 08:10:45 UTC'. Crystal's Time module makes it easy to work with time objects, and the conversion from Unix timestamp to a readable date is straightforward using the Time.unix method.



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