A Ruby port of the popular ms library from Vercel.
Convert human-friendly time strings like "1h", "2 days", "3w", "1.5mo" into milliseconds — and convert milliseconds back into strings.
This gem aims to match the behavior of Vercel/ms, including:
ms("1h") -> 3600000ms(3600000) -> "1h"- Strict and non-strict parsing
- Long and short formatting
- Floating-point and negative values
- Full unit support (ms, s, m, h, d, w, mo, y)
Add to your Gemfile:
gem "ms-rb"Or install directly:
gem install ms-rbThen require it:
require "ms"The main entrypoint is:
Ms.ms(value, long: false)Ms.ms("2h") # => 7200000
Ms.ms("1.5d") # => 129600000
Ms.ms("3 weeks") # => 1814400000
Ms.ms("-10ms") # => -10
Ms.ms("1 s") # => 1000Short form:
Ms.ms(3600000) # => "1h"
Ms.ms(5400000) # => "2h"Long form:
Ms.ms(3600000, long: true) # => "1 hour"
Ms.ms(5400000, long: true) # => "2 hours"Ms.parse_strict("1h") # => 3600000
Ms.parse_strict("foo") # => NaN| Unit(s) | Meaning |
|---|---|
ms, msec, millisecond, milliseconds |
Milliseconds |
s, sec, second, seconds |
Seconds |
m, min, minute, minutes |
Minutes |
h, hr, hour, hours |
Hours |
d, day, days |
Days |
w, week, weeks |
Weeks |
mo, month, months |
Months |
y, yr, year, years |
Years |
Supports floats, negative values, and mixed case:
Ms.ms("1.5H") # => 5400000
Ms.ms("-.5h") # => -1800000
Ms.ms("53 YeArS") # => 1672552800000Main entrypoint. Accepts:
String→ returns milliseconds (IntegerorFloat)Numeric→ returns formatted string ("1h"or"1 hour")
Example:
Ms.ms("2h") # => 7200000
Ms.ms(7200000) # => "2h"
Ms.ms(7200000, long: true) # => "2 hours"Non-strict parser.
Returns NaN for invalid input.
Strict parser.
Raises on invalid input types, returns NaN for malformed strings.
Formats milliseconds directly.
bundle install
bundle exec rake testMIT © Austin Miller