Time and date
| Time.now | |
| Format with strftime | |
| Parse input | |
| Date arithmetic |
Time.now
Time dot now captures the current moment with date and clock time together. Print it during logging to see exactly when events happen.
Time objects compare with plain operators, so finding the later of two moments needs no extra library. Dates often arrive as text, so the string skills from
Encodings
pair well with this lesson.
now = Time.now
puts now
Format with strftime
strftime turns a Time into text using percent codes for year, month, day, hours, and minutes. You arrange the codes with any separators you like.
One format string can serve logs, file names, and screen output without extra helpers.
t = Time.now
puts t.strftime("%Y-%m-%d")
Parse input
The time library adds parsing of common formats. Require it first, then pass the user text to parse.
Invalid text raises an error, so validate around parsing when input comes from strangers.
require "time"
t = Time.parse("2026-10-06")
puts t.year
Date arithmetic
The date library adds calendar math without clock time. today gives the current date, and plus or minus a number shifts by days.
Subtracting two dates gives the gap between them, which to_i turns into whole days.
require "date"
today = Date.today
puts today + 7
Next: JSON and YAML
Article author: Arthur Isaev