ms

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package ms converts between time durations and human readable strings, modeled on the npm "ms" package. It parses strings such as "2h", "1d" or "2.5 days" into time.Durations and formats time.Durations back into short ("2h") or long ("2 hours") forms. The npm original is one of the most widely depended-on utilities in the Node ecosystem, used throughout Express and its middleware for things like cookie max-ages, cache lifetimes and timeout configuration; this package is a standard-library-only Go port of it.

The point of the package is to let humans and configuration files express durations in a friendly notation while your code works with a real time.Duration. You write "30d" or "2.5 hours" in a config value or a command-line flag and Parse turns it into something you can add to a time.Time or hand to a timer. Going the other way, Format and FormatLong turn a computed duration back into a compact label for logs, UIs or error messages. All functions are pure, allocation-light and safe for concurrent use.

Parse works in the "string to duration" direction. It understands an optional sign, an integer or decimal number, optional surrounding spaces and a unit, where the unit may be spelled short (ms, s, m, h, d, w, y) or long (millisecond(s), second(s), minute(s), hour(s), day(s), week(s), year(s)) along with common abbreviations like "secs", "mins" and "hrs". Matching is case-insensitive. A bare number with no unit is interpreted as milliseconds, so Parse("100") is 100 milliseconds, exactly as in the npm package. Years are treated as 365.25 days and weeks as 7 days.

Format and FormatLong work in the "duration to string" direction, which the npm ms package selects with its { long } option. Both pick the largest unit whose absolute magnitude is at least one — days, hours, minutes, seconds or milliseconds — and round to the nearest whole count. Format produces the terse form ("2h", "-1500ms"); FormatLong produces the spelled-out form ("2 hours", "1 minute") with pluralization that, matching the original, switches to the plural name once the magnitude reaches 1.5 units. Negative durations are supported in both directions: Parse accepts a leading "-" and the formatters preserve the sign.

A few edge cases are worth noting for parity with Node. Empty input is an error rather than zero, and an input longer than 100 characters is rejected outright as a guard against pathological strings. Anything that does not match the number-and-optional-unit grammar (an unknown unit, stray letters, multiple numbers) yields an error instead of a silent zero. Unlike the JavaScript version, which returns undefined or NaN on bad input, this port returns an explicit Go error, so callers can decide how to handle malformed values.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Format

func Format(d time.Duration) string

Format returns the short human readable form of d, choosing the largest unit whose magnitude is at least one: days ("d"), hours ("h"), minutes ("m"), seconds ("s") or milliseconds ("ms").

Example

ExampleFormat converts a time.Duration into the terse human-readable form, the direction the npm package uses without its { long } option. Format picks the largest unit whose absolute magnitude is at least one and rounds to the nearest whole count. A two-hour duration becomes "2h" and a sub-second duration stays in milliseconds. Negative durations keep their sign. The example prints several durations to show the unit selection.

package main

import (
	"fmt"
	"time"

	"github.com/malcolmston/express/ms"
)

func main() {
	fmt.Println(ms.Format(2 * time.Hour))
	fmt.Println(ms.Format(500 * time.Millisecond))
	fmt.Println(ms.Format(-3 * time.Second))
}
Output:
2h
500ms
-3s

func FormatLong

func FormatLong(d time.Duration) string

FormatLong returns the long human readable form of d, such as "2 hours" or "1 minute", with correct pluralization.

Example

ExampleFormatLong converts a time.Duration into the spelled-out form, the direction the npm package selects with { long: true }. It chooses the same largest-fitting unit as Format but writes the unit name in full with correct pluralization. Matching the original, a value switches to the plural name once its magnitude reaches 1.5 units, so one hour stays singular while two hours is plural. The example prints a singular and a plural case together.

package main

import (
	"fmt"
	"time"

	"github.com/malcolmston/express/ms"
)

func main() {
	fmt.Println(ms.FormatLong(time.Hour))
	fmt.Println(ms.FormatLong(2 * time.Hour))
	fmt.Println(ms.FormatLong(time.Minute))
}
Output:
1 hour
2 hours
1 minute

func Parse

func Parse(s string) (time.Duration, error)

Parse converts a human readable duration string such as "2h", "1d", "-1.5h", "100" or "2.5 days" into a time.Duration. A bare number is interpreted as milliseconds. It returns an error if the string is empty, unreasonably long, or cannot be parsed.

Example

ExampleParse converts a human-readable duration string into a time.Duration. The input may use a short unit like "h" or a long unit like "days", optionally with a decimal number and surrounding spaces. Parsing is case-insensitive and understands common abbreviations. Here "2 days" becomes a 48-hour duration, which prints in Go's standard duration form. The second return value is a non-nil error only when the input cannot be parsed.

package main

import (
	"fmt"

	"github.com/malcolmston/express/ms"
)

func main() {
	d, err := ms.Parse("2 days")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(d)
}
Output:
48h0m0s
Example (BareNumber)

ExampleParse_bareNumber shows the special rule that a number with no unit is interpreted as milliseconds, matching the npm ms package. This makes "100" mean 100 milliseconds rather than 100 of some larger unit. The rule is handy for configuration values that are already expressed in milliseconds. The parsed duration therefore prints as "100ms". Any explicit unit would override this default.

package main

import (
	"fmt"

	"github.com/malcolmston/express/ms"
)

func main() {
	d, _ := ms.Parse("100")
	fmt.Println(d)
}
Output:
100ms
Example (Negative)

ExampleParse_negative demonstrates that Parse accepts a leading minus sign and decimal values together. The string "-1.5h" is one and a half hours in the past, which is ninety minutes. This is useful for expressing offsets relative to the present. The resulting duration prints in Go's canonical form as a negative hours-and-minutes value. Negative durations round-trip through the formatters as well.

package main

import (
	"fmt"

	"github.com/malcolmston/express/ms"
)

func main() {
	d, _ := ms.Parse("-1.5h")
	fmt.Println(d)
}
Output:
-1h30m0s

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL