Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 134 ยท Standard Library

Time and Date

Learn Ruby's Time and Date classes - creating moments, strftime formatting, arithmetic, parsing ISO 8601, time zones and offsets, calendar math with Date, and the mistakes that bite.

Almost every real program touches dates: when an order was placed, how long a session lasted, which day a subscription renews, whether a year is a leap year. Dates look simple and are surprisingly full of traps: time zones, daylight saving time, months with different lengths, and formats that differ in every country. Ruby gives you two main tools. Time is built into the core and represents a moment (a point on the timeline, down to nanoseconds). Date comes from the standard library (require 'date') and represents a calendar day with no time of day at all.

This lesson shows how to create both, format them with strftime, do arithmetic, parse text, deal with offsets, and avoid the classic mistakes. Because the output of Time.now changes every second, every example here builds its times from fixed numbers, which is also what good tests do (see Testing with Minitest).

Creating a Time

Ruby Time.new, Time.utc and Time.at

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Time.utc builds a time in UTC (also available as Time.gm). Time.new builds one in the local zone unless you give an offset as the seventh argument. Time.now is the current moment. Under the hood a Time is a count of seconds since the Unix epoch, 1970-01-01 00:00:00 UTC, which is why Time.at(0) is that moment and to_i returns the count.

Our runner's local zone is UTC, so Time.new(2026, 1, 1) here gives the same moment as Time.utc(2026, 1, 1) (it just prints +0000 instead of UTC). On your own machine it uses your system's zone. Pass an explicit offset whenever the result must not depend on where the code runs.

Formatting with strftime

strftime ("string format time") turns a time into text using percent codes. You will use a small set of them over and over.

Ruby strftime codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The common codes are %Y (four-digit year), %m (month 01-12), %d (day 01-31), %H (hour 00-23), %M (minute), %S (second), %B and %b (full and short month name), %A and %a (weekday names), %z (offset like +0000) and %Z (zone name). A - after the percent sign removes zero padding, so %-d gives 4 instead of 04. Ruby also has shortcuts such as t.iso8601 after require 'time', which is usually better than writing the format by hand when you exchange data with other systems.

Arithmetic

Adding a number to a Time adds seconds. Subtracting two times gives the difference in seconds as a Float.

Ruby Adding, subtracting and comparing times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Times are Comparable, so <, ==, between?, min, max and sorting all work (see Comparable). Ruby has no built-in "add one month" for Time, because months are not a fixed number of seconds. For that, use Date, which counts calendar units, as shown below.

Do not time things with Time.now - start when you measure code speed: the system clock can jump. Use Process.clock_gettime(Process::CLOCK_MONOTONIC) instead, as shown in Benchmarking.

Parsing text into a Time

Parsing needs require 'time', which adds Time.parse, Time.iso8601, Time.strptime and Time#iso8601.

Ruby Time.parse, iso8601 and strptime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Time.iso8601 accepts only the strict ISO 8601 format and raises ArgumentError (invalid xmlschema format: "tomorrow", the old name of the format) for anything else, which is what you want for data from files or APIs. Time.parse is permissive: it fills in missing parts from the current date and happily accepts strange strings, so prefer iso8601 or strptime whenever the format is known.

Time zones and offsets

A Time carries a UTC offset (like +01:00), not a named zone such as "Europe/Paris" with its daylight saving rules. Ruby's core can convert between UTC, your local zone and fixed offsets:

Ruby Converting between offsets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

All three values are the same instant, so == is true. Only the display differs. Note that zone is nil for a time that has only a fixed offset, because there is no zone name to report, while a UTC time reports "UTC". For named zones with daylight saving rules (America/New_York, Europe/Paris), Ruby's standard library has no database. In real projects people use the tzinfo gem, or Rails's ActiveSupport::TimeWithZone. Both are third-party and not available in this runner, so treat them as read-only here:

Ruby
# read-only example: needs the tzinfo gem
require 'tzinfo'
zone = TZInfo::Timezone.get("Europe/Paris")
zone.utc_to_local(Time.utc(2026, 7, 1, 12, 0, 0))

The safest strategy for most programs: store and compare times in UTC, convert to a local zone only when showing them to a person.

Date: calendar days

Date needs require 'date'. It has no hours or minutes, so it avoids the zone confusion and is the right type for birthdays, due dates and reports by day.

Ruby Date basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

d + 30 adds days. d >> 1 and d.next_month add calendar months, and when the target month is shorter they clamp to the last valid day: January 31 plus one month is February 28, not an error. Subtracting two dates gives a Rational number of days, which you convert with to_i:

Ruby Differences, ranges and parsing dates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Date::Error is a subclass of ArgumentError, so a plain rescue ArgumentError also catches it. Because Date is Comparable and supports succ, a range of dates works with each, map and select, which makes "every Monday in this month" a one-liner.

A worked example: age and next birthday

Putting it together: a method that computes a person's age on a given day, and how many days remain until the next birthday.

Ruby Age and days until birthday

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last call raises on purpose (and the example rescues it) to show a real bug: Date.new(2026, 2, 29) is not a valid date, so a naive birthday method breaks for leap-day babies. The message is just Date::Error: invalid date, the same one Date.parse("not a date") produces. The fix is to decide a rule (for example, treat the birthday as March 1 or February 28 in non-leap years) and write it down in the code. Date bugs like this usually appear only on one day in four years, so tests with fixed dates are essential.

Common pitfalls

  • Time zones on a server. Time.now and Time.new without an offset use the machine's zone, which differs between your laptop and production. Store UTC.
  • Adding 86,400 seconds is not always "one day". In zones with daylight saving, a local day can have 23 or 25 hours. If you mean a calendar day, use Date arithmetic.
  • Float seconds. Time#- returns a Float; compare with a tolerance or use Rational/integers when exactness matters.
  • Date.today versus Time.now.to_date can disagree around midnight in different zones. Pick one source of "today" and pass it in as an argument, as the birthday example did, so you can test it.
  • DateTime still exists but is considered obsolete; use Time for moments and Date for days.
  • Ambiguous formats. 03/04/2026 is March 4 in the US and April 3 in most of the world. Use ISO 8601 (2026-03-04) for data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does adding a number to a Time object, like t + 60, do?

    Time arithmetic works in seconds. To move by calendar days or months, use Date, whose + adds days and >> adds months.
  2. 2. What does Date.new(2026, 1, 31) >> 1 return?

    Adding a month clamps to the last valid day of the target month, so January 31 becomes February 28 in 2026.
  3. 3. Which method should you use to read a timestamp from an API when the format is known to be ISO 8601?

    Time.iso8601 (after require 'time') accepts only the ISO 8601 format and raises ArgumentError otherwise, which protects you from silently misreading data.
  4. 4. Two Time objects, one in UTC and one at +09:00, describe the same instant. What does == return?

    A Time is a point on the timeline; the offset only changes how it is displayed. The hours differ but the moment is equal.
  5. 5. Why is Time.now - start a poor way to measure how long a piece of code runs?

    The wall clock can jump forwards or backwards (clock sync, daylight changes). The monotonic clock from Process.clock_gettime never goes backwards.

Summary

  • Time is a moment (seconds since the epoch, plus an offset); Date is a calendar day. Date needs require 'date', parsing needs require 'time'.
  • Build times from fixed numbers (Time.utc, Time.new with an offset, Time.at) so programs and tests are repeatable.
  • strftime formats with percent codes; %-d removes padding; iso8601 is the best format for exchanging data.
  • Time arithmetic is in seconds; Date arithmetic is in days, and >> / next_month move by calendar months with clamping.
  • Parse strictly with Time.iso8601, Time.strptime and Date.strptime; bad input raises ArgumentError or Date::Error.
  • Store UTC, convert for display, and pass "today" in as an argument.

Next: Random Numbers and Math