How to Work with Dates and Times in Ruby
· 1 min read · Updated March 12, 2026 · beginner
ruby datetime time date cookbook
Ruby gives you several ways to work with dates and times. This cookbook covers the most common patterns.
Getting Current Date and Time
Time.now # => 2026-03-12 20:30:00 +0000
Date.today # => #<Date: 2026-03-12>
Parsing Date Strings
Time.parse("2026-03-12") # Auto-parse
Date.strptime("12/03/2026", "%d/%m/%Y") # Explicit format
Formatting Dates
time = Time.now
time.strftime("%Y-%m-%d") # => "2026-03-12"
time.strftime("%H:%M:%S") # => "20:30:00"
Date Calculations
time = Time.now
time + 86400 # 1 day later
time - 86400 # 1 day ago
# Difference in seconds
later = time + 3600
later - time # => 3600.0
Common Recipes
Age calculation
def age(birthdate)
today = Date.today
age = today.year - birthdate.year
age -= 1 if today.yday < birthdate.yday
age
end
Unix timestamp
time = Time.now
time.to_i # seconds since 1970
Time.at(1700000000) # convert back
Filename timestamps
Time.now.strftime("%Y%m%d_%H%M%S") # => "20260312_203000"
File.mtime("example.txt")
See Also
Array#join— Formatting arrays with separatorsJSON— Parsing JSON timestamps