Current Unix Timestamp SECONDS SINCE JAN 01 1970

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

How to convert Datetime to Unix timestamp in Ruby

🎈 🎈 🎈
+1

    date_time = Time.new(2017, 4, 22, 4, 26, 40)
    unix_timestamp = date_time.to_i
    
    puts "Unix Timestamp: #{unix_timestamp}"
        

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

Code Explanation

In this Ruby example, the Time.new method is used to create a Time object representing the specific date and time 2017-04-22 04:26:40.
The to_i method is then called on this Time object to convert it into a Unix timestamp, which represents the number of seconds since the Unix epoch. The result, 1492835200, is the Unix timestamp corresponding to the given date and time.



Other useful Ruby date functions

Function Description Example
Time.now Returns the current date and time as a Time object. Time.now returns 2024-08-28 12:34:56 -0400
Date.today Returns the current date as a Date object. Date.today returns 2024-08-28
Time.at() Converts a Unix timestamp to a Time object representing the corresponding date and time. Time.at(1698499452) returns 2023-10-28 12:44:12 -0400
Time.new() Creates a new Time object representing the specified date and time. Time.new(2023, 10, 28, 12, 44, 12) returns 2023-10-28 12:44:12 -0400
Time#to_i Returns the Unix timestamp (number of seconds since January 1, 1970) for the given Time object. Time.new(2023, 10, 28, 12, 44, 12).to_i returns 1698499452
Date.parse() Parses a string into a Date object. Date.parse('2023-10-28') returns 2023-10-28
Time.parse() Parses a string into a Time object. Time.parse('2023-10-28 12:44:12') returns 2023-10-28 12:44:12 -0400
DateTime.now Returns the current date and time as a DateTime object. DateTime.now returns 2024-08-28T12:34:56+00:00
DateTime#strftime() Formats the DateTime object according to the given format string. DateTime.now.strftime('%Y-%m-%d %H:%M:%S') returns 2024-08-28 12:34:56
DateTime#to_time Converts a DateTime object to a Time object. DateTime.now.to_time returns 2024-08-28 12:34:56 -0400
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