philiprehberger-duration
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 installOr install directly:
gem install philiprehberger-durationUsage
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 secondsArithmetic
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") # => trueBetween 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 styleLicense
MIT