Time
Added in v1.0 · Updated March 13, 2026 · Modules
ruby stdlib time datetime
The Time class provides methods for working with dates and times in Ruby. It’s part of the standard library and offers powerful date/time manipulation capabilities.
Overview
Ruby’s Time class represents dates and times:
- Create: Generate times from strings, timestamps, or components
- Parse: Convert strings into Time objects
- Manipulate: Add, subtract, and modify time values
- Format: Display times in various formats
Creating Time Objects
Current Time
Time.now # => 2026-03-13 14:52:00 +0000
Time.current # => Same as now, but respects Rails timezone
From String
Time.parse("2026-03-13")
# => 2026-03-13 00:00:00 +0000
Time.parse("2026-03-13 10:30:00")
# => 2026-03-13 10:30:00 +0000
From Components
Time.new(2026, 3, 13, 14, 30, 0)
# => 2026-03-13 14:30:00 +0000
From Timestamp
Time.at(1700000000)
# => 2023-11-14 22:13:20 +0000
Time.at(1700000000, :millisecond)
# => 2023-11-14 22:13:20.000 +0000
Time Components
You can extract individual components from a Time object:
time = Time.now
time.year # => 2026
time.month # => 3
time.day # => 13
time.hour # => 14
time.min # => 52
time.sec # => 0
time.wday # => 5 (0 = Sunday)
time.yday # => 72 (day of year)
time.zone # => "UTC"
Time Calculations
Adding/Subtracting
time = Time.now
time + 3600 # One hour from now
time - 86400 # One day ago
Comparing Times
past = Time.parse("2020-01-01")
future = Time.parse("2030-01-01")
future > past # => true
past <=> future # => -1 (past is earlier)
Formatting Times
strftime
The strftime method formats time using directives:
time = Time.now
time.strftime("%Y-%m-%d") # => "2026-03-13"
time.strftime("%H:%M:%S") # => "14:52:00"
time.strftime("%B %d, %Y") # => "March 13, 2026"
time.strftime("%d/%m/%Y") # => "13/03/2026"
time.strftime("%A") # => "Friday"
| Directive | Meaning | Example |
|---|---|---|
%Y | Year | 2026 |
%m | Month (01-12) | 03 |
%d | Day | 13 |
%H | Hour (24h) | 14 |
%M | Minute | 52 |
%S | Second | 00 |
%A | Weekday | Friday |
%B | Month name | March |
Predefined Formats
time.iso8601 # => "2026-03-13T14:52:00Z"
time.rfc2822 # => "Fri, 13 Mar 2026 14:52:00 +0000"
time.xmlschema # => "2026-03-13T14:52:00Z"
Time Zones
Working with Time Zones
require "time"
# Parse with timezone
Time.parse("2026-03-13 10:00:00 EST")
# => 2026-03-13 10:00:00 -0500
# Get time in specific zone
Time.use_zone("Pacific Time (US & Canada)") do
Time.zone.now
end
Converting Between Zones
time = Time.now.utc
time.getlocal("-0800") # Convert to PST
time.utc # Convert to UTC
Practical Examples
Age Calculation
birthday = Time.parse("1990-06-15")
age = ((Time.now - birthday) / 365.25 / 24 / 60 / 60).to_i
# => 35
Day Start/End
time = Time.now
time.beginning_of_day # => 2026-03-13 00:00:00 +0000
time.end_of_day # => 2026-03-13 23:59:59 +0000
Date Arithmetic
require "date"
date = Date.today
next_week = date + 7
last_month = date << 1