Skip to content
AgileLogics
5 min read

Dates and Times

Prerequisites: Requiring files and libraries

Ruby has two main classes for this: Time (a moment, down to fractions of a second, with a time zone offset) and Date (a calendar day, from the date library).

Time

t = Time.new(2025, 1, 15, 9, 30, 0, "+00:00")

puts t
puts t.year
puts t.strftime("%d/%m/%Y %H:%M")
puts t.strftime("%A, %B %-d")
puts t + 3600
puts t.utc?
puts t.to_i
2025-01-15 09:30:00 +0000
2025
15/01/2025 09:30
Wednesday, January 15
2025-01-15 10:30:00 +0000
false
1736933400
  • Adding a number to a Time adds seconds.
  • strftime formats a time: %Y year, %m month, %d day, %H:%M hours and minutes, %A weekday name, %B month name.
  • to_i gives the Unix timestamp — seconds since 1 January 1970. The Unix Epoch Converter translates these back and forth.

Time.now is the current time, in your computer's time zone.

Date

require "date"

d = Date.new(2025, 2, 27)
puts d + 3
puts d.next_month
puts (Date.new(2025, 12, 25) - d).to_i
puts d.saturday?
puts Date.parse("2025-03-01").strftime("%b %-d, %Y")
puts Date.iso8601("2025-03-01").cwday
2025-03-02
2025-03-27
301
false
Mar 1, 2025
6

Adding a number to a Date adds days, and the calendar is handled for you: February 27 + 3 days is March 2 in 2025.

Time zones

Store and compare times in UTC (Time.now.utc), and convert to a user's local time only when displaying. Full time-zone support by name (such as "Europe/London") needs a gem such as tzinfo — or, in Rails, the built-in ActiveSupport::TimeZone.

Common mistakes

  • Parsing user-entered dates with Date.parse, which guesses the format. Prefer Date.strptime(text, "%d/%m/%Y") with an explicit format, or Date.iso8601 for YYYY-MM-DD input.
  • Storing local times without an offset, then comparing times from different zones.