liveBook · Manning

Time

As explained in The Well-Grounded Rubyist, Fourth Edition

Time is Ruby's built-in class for representing, manipulating, and formatting times and dates.

Ruby's Time class represents moments that can be created, queried, converted, calculated, and formatted. Choose a constructor according to whether you need the current time, epoch-based seconds, local calendar fields, or a parsed string. section 8.4.1 section 8.5

Create Time objects with several practical constructors:

  • Time.new or Time.now returns the current time. section 8.4.1
  • Time.at(seconds) represents seconds since the Unix epoch. section 8.4.1
  • Time.mktime, also called Time.local, accepts calendar and clock fields such as year, month, day, hour, minute, and second. section 8.4.1

Inspecting a moment

A Time object exposes its year, month, day, hour, minute, and second through query methods. For example, t.month and t.sec retrieve components from Time.now; dst? reports daylight-saving-time status, while weekday predicates such as sunday? answer calendar questions. section 8.4.2

Time arithmetic adds or subtracts seconds and returns a new Time object, leaving the original moment available. Time can also convert to Date or DateTime; when the target carries more information, missing fields become zero. Date/time values are commonly formatted with methods such as strftime rather than relying on default string output. section 8.4.4 section 8.4.2 section 8.5

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains constructors, component queries, calendar predicates, arithmetic, conversions, and formatting without exhaustive API coverage.
Examples
Uses Time.now, Time.at, Time.mktime, Time.parse, component queries, weekday predicates, and adding or subtracting seconds.
What you can do after
Apply it via Time constructors, query methods, arithmetic operators, conversions, and strftime-based formatting.
How it connects
Connects Time with Date, DateTime, Unix epoch, calendar arithmetic, scalar objects, and string formatting.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.