Date & Time in Ruby
Work with dates and times in Ruby using the built-in Time, Date, and DateTime classes including formatting, parsing, arithmetic, and time zones.
Introduction to Date & Time
Ruby provides three built-in classes: `Time` (date + time + timezone, always available), `Date` (date only, requires `require "date"`), and `DateTime` (legacy combined class, also requires `require "date"`).
1. Time vs Date vs DateTime
`Time` is the go-to class for most work. `Date` is for calendar operations. `DateTime` is mostly legacy.
Creating Date Objects
Create `Time` objects with `Time.now`, `Time.new`, or `Time.mktime`. Create `Date` objects with `Date.today`, `Date.new`, or `Date.parse`.
1. Time.new and Time.now
`Time.now` gets the current time; `Time.new` builds a specific moment.
2. Date.new and Date.parse
`Date.new` builds from year/month/day; `Date.parse` parses a string.
3. Time.utc
`Time.utc` creates a time in UTC (Coordinated Universal Time).
Timestamps
A Unix timestamp is the number of seconds since January 1, 1970 (the Unix epoch). Use `Time#to_i` to get it and `Time.at` to convert back.
1. Unix Timestamps
`to_i` converts a Time to a Unix timestamp; `Time.at` reverses it.
Getting Date Components
`Time` and `Date` objects expose individual components as methods.
1. Time Components
Extract individual parts of a Time object.
2. Date Components
`Date` objects expose `year`, `month`, `day`, `wday`, and more.
Formatting Dates
`strftime` formats a date or time using format codes. `to_s` gives ISO 8601 format.
1. strftime — Custom Format
`strftime` converts a date/time to a string using format specifiers.
2. to_s and iso8601
`to_s` gives a default string; `iso8601` gives the ISO 8601 format.
Comparing Dates
Use `<`, `>`, `==`, and `<=>` to compare Time and Date objects.
1. Comparison Operators
Date and Time objects support all comparison operators.
2. between? and clamp
`between?` checks if a date falls within a range.
Date Arithmetic
`Date` supports `+` and `-` with integers (days). `Time` uses seconds. Both support `next_day`, `prev_day`, and similar helpers.
1. Adding and Subtracting Days
`Date + n` adds n days; `Date - n` subtracts n days.
2. Adding Seconds to Time
`Time + seconds` adds that many seconds.
Timezones & UTC
Ruby's `Time` class supports UTC and local time. Use `utc`, `localtime`, and `getutc` to convert between them.
1. UTC and Local Time
Convert a time between UTC and local timezone.
2. Best Practice — Store in UTC
Always store and compare times in UTC. Convert to local only for display.
Best Practices
Avoid common pitfalls with timezones, parsing, and date arithmetic.
1. Prefer Time over DateTime
`DateTime` is a legacy class. Use `Time` for all date+time work.
2. Parse Dates Safely
Use `Date.parse` or `Time.parse` inside a rescue block for user input.