Convert Figma logo to code with AI

vercel logoms

Tiny millisecond conversion utility

5,137
264
5,137
29

Top Related Projects

Convert milliseconds to a human readable string: `1337000000` → `15d 11h 23m 20s`

Quick Overview

Vercel/ms is a tiny JavaScript library for converting various time formats to milliseconds. It provides a simple and efficient way to parse time strings and convert them to milliseconds, making it useful for time-based calculations and operations in JavaScript applications.

Pros

  • Lightweight and minimalistic, with no dependencies
  • Supports a wide range of time formats and units
  • Easy to use and integrate into existing projects
  • Well-maintained and actively supported by the community

Cons

  • Limited functionality beyond time conversion to milliseconds
  • May require additional libraries for more complex time operations
  • Not suitable for handling timezone-specific calculations
  • Lacks support for parsing complex date formats

Code Examples

Converting time strings to milliseconds:

const ms = require('ms');

console.log(ms('2 days'));  // Output: 172800000
console.log(ms('1h'));      // Output: 3600000
console.log(ms('10s'));     // Output: 10000

Converting milliseconds to human-readable strings:

const ms = require('ms');

console.log(ms(60000));        // Output: '1m'
console.log(ms(2 * 60 * 1000)); // Output: '2m'
console.log(ms(ms('1d')));     // Output: '1d'

Using ms for relative time calculations:

const ms = require('ms');

const now = Date.now();
const futureDate = now + ms('2 weeks');
console.log(new Date(futureDate).toISOString());

Getting Started

To use vercel/ms in your project, follow these steps:

  1. Install the library using npm:

    npm install ms
    
  2. Import and use the library in your JavaScript code:

    const ms = require('ms');
    
    // Convert time string to milliseconds
    const milliseconds = ms('1h 30m');
    console.log(milliseconds); // Output: 5400000
    
    // Convert milliseconds to human-readable string
    const timeString = ms(5400000);
    console.log(timeString); // Output: '1.5h'
    

That's it! You can now use the ms function to convert between time strings and milliseconds in your project.

Competitor Comparisons

Convert milliseconds to a human readable string: `1337000000` → `15d 11h 23m 20s`

Pros of pretty-ms

  • Offers more detailed and customizable output formatting
  • Supports localization options for different languages
  • Includes additional features like compact mode and verbose output

Cons of pretty-ms

  • Larger package size due to additional features
  • May have a slightly steeper learning curve for basic use cases
  • Potentially slower performance for simple time conversions

Code Comparison

ms:

ms('2 days')  // 172800000
ms('1d')      // 86400000
ms('10h')     // 36000000
ms('2.5 hrs') // 9000000
ms('2h')      // 7200000

pretty-ms:

prettyMs(1337000000) // '15d 11h 23m 20s'
prettyMs(1337)       // '1.3s'
prettyMs(133)        // '133ms'
prettyMs(1337, {compact: true}) // '15d 11h'
prettyMs(1337, {verbose: true}) // '1 second 337 milliseconds'

ms is a lightweight library focused on simple millisecond conversions, while pretty-ms offers more advanced formatting options and customization. ms is ideal for basic time parsing and conversion, whereas pretty-ms excels in generating human-readable time strings with various options. The choice between the two depends on the specific requirements of your project and the level of formatting control needed.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

ms

CI Edge Runtime Compatible

Use this package to easily convert various time formats to milliseconds.

Examples

ms('2 days')  // 172800000
ms('1d')      // 86400000
ms('10h')     // 36000000
ms('2.5 hrs') // 9000000
ms('2h')      // 7200000
ms('1m')      // 60000
ms('5s')      // 5000
ms('1y')      // 31557600000
ms('100')     // 100
ms('-3 days') // -259200000
ms('-1h')     // -3600000
ms('-200')    // -200

Convert from Milliseconds

ms(60000)             // "1m"
ms(2 * 60000)         // "2m"
ms(-3 * 60000)        // "-3m"
ms(ms('10 hours'))    // "10h"

Time Format Written-Out

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"

Features

  • Works both in Node.js and in the browser
  • If a number is supplied to ms, a string with a unit is returned
  • If a string that contains the number is supplied, it returns it as a number (e.g.: it returns 100 for '100')
  • If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned

TypeScript support

As of v3.0, this package includes TypeScript definitions.

For added safety, we're using Template Literal Types (added in TypeScript 4.1). This ensures that you don't accidentally pass ms values that it can't process.

This won't require you to do anything special in most situations, but you can also import the StringValue type from ms if you need to use it.

import ms, { StringValue } from 'ms';

// Using the exported type.
function example(value: StringValue) {
  ms(value);
}

// This function will only accept a string compatible with `ms`.
example('1 h');

In this example, we use a Type Assertion to coerce a string.

import ms, { StringValue } from 'ms';

// Type assertion with the exported type.
function example(value: string) {
  try {
    // A string could be "wider" than the values accepted by `ms`, so we assert
    // that our `value` is a `StringValue`.
    //
    // It's important to note that this can be dangerous (see below).
    ms(value as StringValue);
  } catch (error: Error) {
    // Handle any errors from invalid values.
    console.error(error);
  }
}

// This function will accept any string, which may result in a bug.
example('any value');

You may also create a custom Template Literal Type.

import ms from 'ms';

type OnlyDaysAndWeeks = `${number} ${'days' | 'weeks'}`;

// Using a custom Template Literal Type.
function example(value: OnlyDaysAndWeeks) {
  // The type of `value` is narrower than the values `ms` accepts, which is
  // safe to use without coercion.
  ms(value);
}

// This function will accept "# days" or "# weeks" only.
example('5.2 days');

Advanced Usage

As of v3.0, you can import parse and format separately.

import { parse, format } from 'ms';

parse('1h'); // 3600000

format(2000); // "2s"

If you want strict type checking for the input value, you can use parseStrict.

import { parseStrict } from 'ms';

parseStrict('1h'); // 3600000

function example(s: string) {
  return parseStrict(str); // tsc error
}

Edge Runtime Support

ms is compatible with the Edge Runtime. It can be used inside environments like Vercel Edge Functions as follows:

// Next.js (pages/api/edge.js) (npm i next@canary)
// Other frameworks (api/edge.js) (npm i -g vercel@canary)

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',
};

Related Packages

  • ms.macro - Run ms as a macro at build-time.

Caught a Bug?

  1. Fork this repository to your own GitHub account and then clone it to your local device
  2. Link the package to the global module directory: npm link
  3. Within the module you want to test your local development instance of ms, just link it to the dependencies: npm link ms. Instead of the default one from npm, Node.js will now use your clone of ms!

As always, you can run the tests using: npm test

NPM DownloadsLast 30 Days