rubyguides

How to Work with Dates and Times in Ruby

Ruby gives you several ways to work with dates and times. This cookbook covers the most common patterns.

When you work with dates in Ruby, the biggest decision is usually which class matches the job. Time is a good fit for timestamps and clock-based arithmetic, while Date is better when you care about calendar days without a clock attached. That distinction keeps code honest about what it is measuring. A reminder that says “tomorrow at 9” and a report that says “the third of March” are not the same kind of value, even if they both start from a human-facing date.

The examples below stay small on purpose so each task has a clear shape: get the current moment, parse a known string, print a format, or add and subtract a day. That makes the cookbook easy to scan when you already know the kind of date work you need. If you later need more complicated calendar logic, the same classes still apply, but the mental model starts here.

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 separators
  • JSON — Parsing JSON timestamps