The project is in a healthy, maintained state
Parse human strings and ISO 8601 durations, perform arithmetic and comparison, and output to human-readable or ISO 8601 formats.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies
 Project Readme

philiprehberger-duration

Tests Gem Version License

Immutable Duration value object — parse human strings and ISO 8601, perform arithmetic and comparison, and format output.

Requirements

  • Ruby >= 3.1

Installation

Add to your Gemfile:

gem "philiprehberger-duration"

Then run:

bundle install

Or install directly:

gem install philiprehberger-duration

Usage

require "philiprehberger/duration"

d = Philiprehberger::Duration.parse("2h 30m")
d.to_seconds   # => 9000.0
d.to_human     # => "2 hours, 30 minutes"
d.to_iso8601   # => "PT2H30M"

Parsing

Duration = Philiprehberger::Duration

Duration.parse("1 day 3 hours")   # human string
Duration.parse("PT2H30M")         # ISO 8601
Duration.parse(3600)              # numeric seconds

Arithmetic

d1 = Duration.parse("2h")
d2 = Duration.parse("30m")

d1 + d2   # => Duration("2 hours, 30 minutes")
d1 - d2   # => Duration("1 hour, 30 minutes")
d2 * 3    # => Duration("1 hour, 30 minutes")
d1 / 2    # => Duration("1 hour")

Comparison

Duration.parse("2h") > Duration.parse("1h")   # => true
Duration.parse("60m") == Duration.parse("1h")  # => true

Between Two Times

Duration.between(start_time, end_time).to_human  # => "3 hours, 15 minutes"

API

Method Description
Duration.parse(input) Parse human string, ISO 8601, or numeric seconds
Duration.between(time_a, time_b) Duration between two Time objects
#to_seconds Total seconds as float
#to_human Human-readable string
#to_iso8601 ISO 8601 formatted string
#+, #-, #*, #/ Arithmetic operations
<, >, ==, <=> Comparison (via Comparable)

Development

bundle install
bundle exec rspec      # Run tests
bundle exec rubocop    # Check code style

License

MIT