duration_format/go
Parse and format durations using Go’s time.ParseDuration grammar.
The same format is also used by Prometheus, Kubernetes, HashiCorp tools (Terraform, Consul, Nomad), and InfluxDB — there is no formal specification beyond Go’s docs.
Grammar
duration = [ sign ] component { component } | [ sign ] "0"
sign = "+" | "-"
component = number unit
number = digits [ "." digits ] | "." digits
unit = "ns" | "us" | "µs" | "μs" | "ms" | "s" | "m" | "h"
µs is U+00B5 (micro sign — what Go emits); μs is U+03BC (Greek
small mu) and is accepted on input but never produced.
Examples
go.parse("1h30m")
// -> Ok(duration.nanoseconds(5_400_000_000_000))
go.parse("-2m3.4s")
// -> Ok(duration.nanoseconds(-123_400_000_000))
go.parse("1d")
// -> Error(UnknownUnit("d"))
go.to_string(duration.nanoseconds(5_400_000_000_000))
// -> "1h30m0s"
Types
Reasons a duration string can fail to parse.
pub type Error {
InvalidDuration
MissingUnit
UnknownUnit(String)
Overflow
}
Constructors
-
InvalidDurationThe input was empty, contained only a sign, or otherwise had no recognisable component.
-
MissingUnitA numeric component was followed by no unit (e.g.
"3"). -
UnknownUnit(String)A numeric component was followed by an unrecognised unit. Carries the offending unit string (e.g.
"d"from"1d"). -
OverflowThe total magnitude would exceed Go’s int64 nanosecond range.
Values
pub fn parse(input: String) -> Result(duration.Duration, Error)
Parse a duration string in Go’s time.ParseDuration format.
See the module documentation for the accepted grammar.
pub fn to_string(d: duration.Duration) -> String
Format a duration using Go’s Duration.String() rules.
Zero formats as "0s". Sub-second magnitudes use the largest unit that
keeps a non-zero leading digit (ns, µs, ms). One-second-and-up emits
<h>h<m>m<s>s with trailing zero units omitted and a fractional seconds
component when needed.