How to Get Current Time in Ruby: Simple Syntax and Examples
In Ruby, you can get the current time by calling
Time.now. This returns the current date and time as a Time object representing your system's local time.Syntax
The basic syntax to get the current time in Ruby is Time.now. Here:
Timeis a built-in Ruby class for handling dates and times.nowis a class method that returns the current local time as aTimeobject.
ruby
current_time = Time.now puts current_time
Output
2024-06-01 12:34:56 +0000
Example
This example shows how to get the current time and print it in a friendly format. It demonstrates creating a Time object and using strftime to format the output.
ruby
current_time = Time.now formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S") puts "Current time is: #{formatted_time}"
Output
Current time is: 2024-06-01 12:34:56
Common Pitfalls
One common mistake is expecting Time.now to return UTC time. It returns local system time by default. To get UTC time, use Time.now.utc.
Also, avoid using Time.new without arguments expecting current time; it returns the current time, not the epoch time.
ruby
wrong_time = Time.new(0) puts "Epoch time: #{wrong_time}" correct_time = Time.now puts "Correct current time: #{correct_time}"
Output
Epoch time: 1970-01-01 00:00:00 +0000
Correct current time: 2024-06-01 12:34:56 +0000
Quick Reference
| Method | Description |
|---|---|
| Time.now | Returns current local time |
| Time.now.utc | Returns current time in UTC |
| Time.new | Creates a new Time object for current time if no args |
| Time#strftime(format) | Formats time as string with given pattern |
Key Takeaways
Use
Time.now to get the current local time in Ruby.To get the current UTC time, use
Time.now.utc.Avoid using
Time.new without arguments expecting epoch time; it returns current time.Use
strftime to format the time output as needed.The
Time object holds both date and time information.