Overview
Formatting is the process of converting a numeric duration (in milliseconds) into a human-readable string. Enhanced MS provides theformatMilliseconds() function and the ms() factory function to handle this conversion with extensive customization options.
How formatting works
The formatting process follows four main steps:1. Parsing milliseconds
First, the formatter breaks down the total milliseconds into individual time units usingparseMilliseconds() (~/workspace/source/src/format/helpers/parse-milliseconds.ts:28):
includedUnits are calculated. Units not included receive a null value.
2. Filtering units
Next, the formatter filters out units based on your options (~/workspace/source/src/format/index.ts:49):- Units with
nullvalues are always removed - Units with
0values are removed unlessincludeZero: true
3. Formatting individual units
Each remaining unit is formatted usingformatUnit() (~/workspace/source/src/format/helpers/format-unit.ts:18):
- Pluralization (“1 hour” vs “2 hours”)
- Abbreviations (“h” vs “hour”)
- Minimum digits with zero padding
- Language-specific unit names
4. Joining units
Finally, all formatted units are joined using theunitSeparator (~/workspace/source/src/format/index.ts:70):
Basic usage
- Using formatMilliseconds
- Using ms() factory
Format options
You can customize the output using various options defined in ~/workspace/source/src/format/helpers/resolve-options.ts:5:useAbbreviations
Use short abbreviations instead of full unit names:unitLimit
Limit the number of units displayed:Setting
unitLimit: -1 displays all available units (this is the default).includeZero
Include units with zero values:includedUnits
Specify which time units to include:unitSeparator
Customize the separator between units:hideUnitNames
Display only the numeric values:minimumDigits
Pad numbers with zeros:Format presets
Enhanced MS includes built-in presets for common use cases (~/workspace/source/src/format/helpers/resolve-options.ts:160):short
Abbreviated format with 2 units:fullPrecision
Includes all precision levels down to nanoseconds:colonNotation
Clock-style format (HH:MM:SS):You can extend presets by using the
extends option:Edge cases
The formatter handles various edge cases:Invalid input
Returnsnull for invalid durations:
Empty results
If all units are filtered out, returnsnull:
Related concepts
- Parsing - Convert strings back to milliseconds
- Localization - Use different languages for formatting