ms

repository·main·Indexed 26 days ago

https://github.com/vercel/ms

A tiny millisecond conversion utility for converting human-readable time strings (e.g., '2 days', '1h') into milliseconds and vice versa. Version 4.0.0 supports TypeScript, Edge Runtimes, and provides functions like ms(), parse(), format(), and parseStrict() for flexible time duration handling.

Tokens
1.6K
Snippets
9
Records
16
Agent score
91%

What's inside ms

  1. Use ms in Edge Runtimes

    main

    ms is compatible with the Edge Runtime (e.g., Vercel Edge Functions).

    // Example for Next.js (pages/api/edge.js)
    import { ms } from 'ms';
    const start = Date.now();
    
    export default (req) => {
      return new Response(`Alive since ${ms(Date.now() - start)}`);
    };
    
    export const config = {
      runtime: 'experimental-edge',
    };
  2. Use parse and format helper functions

    main

    For more granular control, you can import parse to convert strings to milliseconds and format to convert milliseconds to short-form strings.

    import { parse, format } from 'ms';
    
    parse('1h'); // 3600000
    format(2000); // "2s"
  3. Format time as written-out strings

    main

    To get a human-readable, long-form string instead of a short unit (e.g., '1 minute' instead of '1m'), pass { long: true } in the options object.

    ms(60000, { long: true })             // "1 minute"
    ms(2 * 60000, { long: true })         // "2 minutes"
    ms(-3 * 60000, { long: true })        // "-3 minutes"
    ms(ms('10 hours'), { long: true })    // "10 hours"
  4. Convert time strings to milliseconds with ms()

    main

    Use the ms function to convert human-readable time strings (e.g., '2 days', '1h', '5s') into their millisecond equivalent. If a string contains only a number, it returns that number. Fractional values like 0.5m are supported.

    ms('2 days')  // 172800000
    ms('1d')      // 86400000
    ms('10h')     // 3600000
    ms('2.5 hrs') // 9000000
    ms('1m')      // 60000
    ms('5s')      // 5000
    ms('100')     // 100
    ms('-1h')     // -3600000
  5. Use parseStrict for enhanced type safety

    main

    If you require strict type checking for input values, use parseStrict. This is useful when you want to ensure the input string adheres to the expected format at a type level.

    import { parseStrict } from 'ms';
    
    parseStrict('1h'); // 3600000
    
    function example(s: string) {
      return parseStrict(s); // tsc error if s is just any string
    }
  6. Convert milliseconds to time strings with ms()

    main

    If you pass a number to ms, it returns a string representing that duration with a unit (e.g., 60000 becomes '1m').

    ms(60000)             // "1m"
    ms(2 * 60000)         // "2m"
    ms(-3 * 60000)        // "-3m"
    ms(ms('10 hours'))    // "10h"
  7. Configure tsdown build settings

    main

    Use defineConfig from tsdown to specify the build configuration for the project. This includes defining entry points, output formats, declaration file generation, and cleaning the output directory.

    import { defineConfig } from 'tsdown';
    
    export default defineConfig({
      entry: ['src/index.ts'],
      format: ['esm'],
      dts: true,
      clean: true,
    });
  8. Supported time units in ms

    main

    The following units are supported in various forms (lowercase, uppercase, capitalized, with or without spaces):

    • Years: years, year, yrs, yr, y
    • Months: months, month, mo
    • Weeks: weeks, week, w
    • Days: days, day, d
    • Hours: hours, hour, hrs, hr, h
    • Minutes: minutes, minute, mins, min, m
    • Seconds: seconds, second, secs, sec, s
    • Milliseconds: milliseconds, millisecond, msecs, msec, ms

    If no unit is provided (e.g., ms('100')), it defaults to Milliseconds.

  9. Convert between time strings and milliseconds with ms()

    main

    The ms() function is a dual-purpose utility that can either parse a time string into milliseconds or format a number of milliseconds into a human-readable string.

    • To parse: Pass a StringValue (e.g., '2 days', '1h'). It returns a number representing milliseconds.
    • To format: Pass a number. It returns a string representing the duration.

    Use the options object to control the output format:

    • long: true: Returns a verbose string (e.g., '2 days').
    • long: false (default): Returns a short string (e.g., '2d').
  10. Parse time strings using parse()

    main

    The parse(str) function converts a time duration string into its millisecond equivalent.

    • Supported Units: years (y, yrs), months (mo), weeks (w), days (d), hours (h, hrs), minutes (m, mins), seconds (s, secs), and milliseconds (ms, msecs).
    • Return Value: Returns the number of milliseconds, or NaN if the string cannot be parsed.
    • Constraints: The input string must be between 1 and 99 characters long. It throws an error if the string is empty, too long, or contains an unknown unit.
  11. Format milliseconds using format()

    main

    The format(ms, options) function converts a number of milliseconds into a human-readable string.

    • Options:
      • long?: boolean: If true, uses verbose formatting (e.g., '1 hour'). If false or omitted, uses short formatting (e.g., '1h').
    • Errors: Throws an error if the input is not a finite number.