Tiny millisecond conversion utility

Overview

ms

CI

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

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

Comments
  • My code will not run after importing ms

    My code will not run after importing ms

    Since installing ms with npm, I get the following error:

    node main.js /home/runner/RamenBot/node_modules/ms/dist/index.cjs:16 return options?.long ? fmtLong(value) : fmtShort(value); ^

    SyntaxError: Unexpected token '.' at wrapSafe (internal/modules/cjs/loader.js:915:16) at Module._compile (internal/modules/cjs/loader.js:963:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) at Module.load (internal/modules/cjs/loader.js:863:32) at Function.Module._load (internal/modules/cjs/loader.js:708:14) at Module.require (internal/modules/cjs/loader.js:887:19) at require (internal/modules/cjs/helpers.js:74:18) at Object. (/home/runner/RamenBot/commands/mute.js:1:12) at Module._compile (internal/modules/cjs/loader.js:999:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) exit status 1

    (This is on repl.it btw, for some reason it works on vsc but not repl.it, it also won't run on heroku either)

    opened by KNCI-Github 15
  • Add `fromNow`

    Add `fromNow`

    This is a very common pattern in my code. Not sure about how other people use it.

    Date.now() + ms('2h')
    

    I'd love to add fromNow as shortcut.

    const inTwoHours = ms.fromNow('2h'); // 1508165682168 ;)
    

    Yay or nay?

    opened by moeriki 14
  • Shorthand

    Shorthand "m" should be "min"

    The "shorthand" m stands for metre, not minute (whose symbol is min). Using m is confusing, as not only is "metres" meaningless in the context of time, but if standards are not being followed, it can just as easily stand for "months" (whose conventional abbreviation is mo). The output from fmtShort for minutes should be changed to min. Also, there should be a space between the number and the unit symbol in the output from the function as per the SI.

    opened by getsnoopy 13
  • Improve performance and remove str limit

    Improve performance and remove str limit

    Changing the Regex from: /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i to: /^((?:\d+)?\.?\d+) *(\w{0,12})?$/i seems to produce better performance and solve the issues with long str.

    Benchmark source

    original x 38,472 ops/sec ±2.05% (88 runs sampled)
    mine x 74,820 ops/sec ±1.84% (84 runs sampled)
    Fastest is mine
    Done in 17.97s.
    
    opened by thevtm 13
  • TypeScript import without 'esModuleInterop'

    TypeScript import without 'esModuleInterop'

    When importing into TypeScript file with @types/ms installed I am getting:

    TS2497: This module can only be referenced with ECMAScript imports/exports by turning on the 'esModuleInterop' flag and referencing its default export.
    

    Sure, I can turn esModuleInterop, but no other module I used had this issue.

    Fix can be maybe to update code?

    opened by Baterka 9
  • Limit str to 100 to avoid ReDoS of 0.3s

    Limit str to 100 to avoid ReDoS of 0.3s

    Hey, The fix for CVE-2015-8315 was incomplete. Limiting the input to 10,000 chars reduced the risk significantly but it is still possible to cause a delay of 0.3s. Suggested to limit it to 100 chars as there is no reason for a date to be over that :)

    PoC:

    ms=require('ms');
    ms('1'.repeat(9998) + 'Q')
    //Takes about ~0.3s
    

    Thanks, Karen Yavine Security Analyst @ snyk.io

    opened by karenyavine 9
  • Updated dependencies, switch to ESM and require node 12.20

    Updated dependencies, switch to ESM and require node 12.20

    Closes #159

    Personally i don't see any reason for converting it to TypeScript. JSDoc works just as well for providing typing support. ...and dose not require compiling so importing it to Deno with http import gives you typing with ease as well as making it possible to import it using http loader from browsers and nodes new HTTP loader

    opened by jimmywarting 6
  • Fix fmtShort output

    Fix fmtShort output

    Previously, the output from the fmtShort function did not have a space between the quantity and the unit symbol, which is incorrect. It also had the symbol for the minute as "m", which is also incorrect. This commit fixes both of these issues.

    Fixes #134

    opened by getsnoopy 6
  • Add default export

    Add default export

    Make ES module - compatible and allow TypeScript users to easily use the package.

    This will work after merging the PR:

    import ms from 'ms'
    

    I am not a big fan of those double CJS / ES exports myself, but there are a couple of scenarios when you have basically got no other choice.

    opened by andywer 6
  • Added colon separated time support

    Added colon separated time support

    This branch covers #24.

    I don't know why @stuartpb closed his pull request, but I wanted to mention him anyway. Because I just refactored his code block a little bit and added some tests to cover the feature.

    opened by barinali 6
  • https://snyk.io/vuln/npm:ms:20170412 possible fix

    https://snyk.io/vuln/npm:ms:20170412 possible fix

    May split to 2 regular matchers

    var testScale=/^milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y$/i;
    function parse(str) {
      str = String(str);
      if (str.length > 10000) {
        return;
      }
      var match = /^((?:\d+)?\.?\d+)\s*(\w*)$/i.exec(
        str
      );
      if (!match) {
        return;
      }
      if(match[2] && !testScale.test(match[2])){
        return;
      }
    

    with test

    describe("CWE-400", function (){
      it('should break if longer than 50ms', function() {
        this.timeout(50);
        ms('1'.repeat(9998) + 'Q');
      });
    });
    
    opened by Delagen 6
  • The package is just showing the time in days

    The package is just showing the time in days

    When I try to convert milliseconds, it just shows the number of days and no hours are shown. Like the actual is 5 days 3 hours. But it shows 5 days only

    opened by Beast12335 0
  • fix(typing): Could not find a declaration file for module 'ms'.

    fix(typing): Could not find a declaration file for module 'ms'.

    Hi!

    I faced this issue.

    Could not find a declaration file for module 'ms'. '/Users/ocean/main/haetae/node_modules/.pnpm/[email protected]/node_modules/ms/index.js' implicitly has an 'any' type.
      Try `npm i --save-dev @types/ms` if it exists or add a new declaration (.d.ts) file containing `declare module 'ms';`ts(7016)
    
    스크린샷 2022-07-24 오후 3 41 59

    Currently, my project is written in typescript and to be compiled to CJS.

    Reproduction

    $ git clone [email protected]:jjangga0214/haetae.git
    $ cd haetae 
    $ git reset --hard 5e8e501
    $ pnpm install
    $ cd packages/core
    $ vi src/index.ts # And then remove @ts-ignore from the source file
    $ pnpm tsc --noEmit
    

    Info

    • os: macOS 12.4
    • node: 16.13.1
    • pnpm: 7.5.1

    Thanks!

    opened by jjangga0214 1
  • 'esModuleInterop' flag and referencing its default export.ts

    'esModuleInterop' flag and referencing its default export.ts

    This module can only be referenced with ECMAScript imports/exports by turning on the 'esModuleInterop' flag and referencing its default export.ts(2497)

    image

    opened by productdevbook 3
  • Release of v3.0.0

    Release of v3.0.0

    Hello, I think it's quite awesome that this package is now written in TypeScript! Since it's been over half a year since the last v3 canary, I would like to ask whether a final release is planned yet.

    opened by meyfa 12
  • Support optional rounding

    Support optional rounding

    This PR enables rounding through the roundoption.

    round defaults to true and current solutions will continue to behave the same.

    When round is set to false, all rounding is disabled.

    When round is set to a number, it is used as precision for toFixed.

    opened by CasperEngl 7
Releases(3.0.0-canary.1)
  • 3.0.0-canary.1(Sep 15, 2021)

  • 3.0.0-canary.0(Sep 15, 2021)

  • 2.1.3(Dec 8, 2020)

    Patches

    • Rename zeit to vercel: #151
    • Bump eslint from 4.12.1 to 4.18.2: #122
    • Add prettier as a dev dependency: #135 #153
    • Use GitHub Actions CI: #154

    Credits

    Huge thanks to @getsnoopy for helping!

    Source code(tar.gz)
    Source code(zip)
  • 2.1.2(Jun 6, 2019)

    Patches

    • Fixed negative decimals less than -10 don't work: #111
    • Support error in case of Infinity: #116
    • Update regexp for 10-.5 is invalid input: #117
    • Update chat badge: #119

    Credits

    Huge thanks to @yuler and @7ma7X for helping!

    Source code(tar.gz)
    Source code(zip)
  • 2.1.1(Nov 30, 2017)

  • 2.1.0(Nov 30, 2017)

    Minor Changes

    • Add "week" / "w" support: a2caead13ac7f9931338a1a51ab4e36ddb505e00
    • Fixed match regex to support negative numbers: #96

    Patches

    • Applied a few text improvements: 15dc8c5b5a9e8372555400485a749ec04cc02444
    • Fixed spelling of “millisecond” in description: #95
    • Lockfile added: 2425ebdefcdd1c2b726c06f6a65c4f2dea58dee7

    Credits

    Huge thanks to @yoavmmn and @binki for helping!

    Source code(tar.gz)
    Source code(zip)
  • 2.0.0(May 16, 2017)

    Major Changes

    • Limit str to 100 to avoid ReDoS of 0.3s: #89

    Patches

    • Ignored logs coming from npm: b1eaab752203e978492a4d540a7ae1d26e6306b1
    • Bumped dependencies to the latest version: bcf57157678fd5afc691383145a35e116f9704d0
    • Invalidated cache for slack badge: 94b995c1d6d5d13ec976a0c6849a3cca9b277e6b

    Credits

    Huge thanks to @karenyavine for their help!

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Mar 19, 2017)

    Major Changes

    • Removed component specification: 1fbbe974cdcad96e592dcb65a7b2a8649f690420

    Patches

    • Test on LTS version of Node: c9b1fd319f0f9198d85ecf4ba83e46cc1216be04
    • Removed XO: 94068ea6d518387670df277f740b1abada80ed48
    • Use prettier and eslint: 57b3ef8e3423cae6254f94c5564a11b4492cff43
    • Badge for XO removed: 389840b329436117741b2ef13a172725082695b9
    • Removed browser testing: e818c3581aca3119c00d81901bfe8fe653bcfda4
    • More suitable name for file containing tests: ee91f307a8dc3581ebdad614ec0533ddb3d8bf56
    Source code(tar.gz)
    Source code(zip)
  • 0.7.3(Mar 8, 2017)

    Patches

    • Mark "options" param as optional in jsdoc: #77
    • Lowercased text files: 5f0653ab192a30301aed8668b4588a87975b41ab
    • Pinned dependencies: 126d7f094a1836b991c8d0abfeb4d0ce09ac280f
    • Chore(package): update serve to version 5.0.1: #81

    Credits

    Huge thanks to @Jokero for their help!

    Source code(tar.gz)
    Source code(zip)
  • 0.7.2(Oct 25, 2016)

    Patches 💅

    • Added license field to package.json file: https://github.com/zeit/ms/pull/42
    • Renamed long and short (reserved keywords): https://github.com/zeit/ms/pull/53
    • Capitalized important files: b2d9f9d
    • Specified version numbers for devDependencies in package.json: abd3616
    • Updated license file to the latest version: 5d53ae8
    • Only upload important files to npm, instead of excluding certain ones: 2b2f02a
    • Adjusted name of repository in package.json: e84f95d
    • Made the package description match the repo's: 3961c12
    • Added details on how to contribute: 201c805 and 73f34c3
    • Fixed the description in README.md: 171f287
    • Updated component file with the latest data: https://github.com/zeit/ms/issues/45
    • Proper structure for README.md: f95bf41
    • Replaced HISTORY.md with Github Releases: 4002de0
    • Removed Makefile in favor of npm scripts: beff285
    • The main test file is now called "index.js": 4dd33d7
    • Started testing in Travis CI: e1066db, 2458287 and 32063f2
    • Added XO as a linting tool: https://github.com/zeit/ms/pull/64 and d0ddfbb
    • Now throwing an error if value is invalid: https://github.com/zeit/ms/pull/52
    • Added examples for converting years: https://github.com/zeit/ms/pull/63
    Source code(tar.gz)
    Source code(zip)
  • 0.7.1(Sep 4, 2016)

  • 0.7.0(Sep 4, 2016)

  • 0.6.2(Sep 4, 2016)

  • 0.6.1(Sep 4, 2016)

  • 0.6.0(Sep 4, 2016)

  • 0.5.1(Sep 4, 2016)

  • 0.5.0(Sep 4, 2016)

  • 0.4.0(Sep 4, 2016)

  • 0.3.0(Sep 4, 2016)

  • 0.2.0(Sep 4, 2016)

    • Add component.json [visionmedia]
    • Add days support [visionmedia]
    • Add hours support [visionmedia]
    • Add minutes support [visionmedia]
    • Add seconds support [visionmedia]
    • Add ms string support [visionmedia]
    • Refactor tests to facilitate ms(number) [visionmedia]
    Source code(tar.gz)
    Source code(zip)
Owner
Vercel
Develop. Preview. Ship. Creators of Next.js.
Vercel
⏳ Modern JavaScript date utility library ⌛️

date-fns provides the most comprehensive, yet simple and consistent toolset for manipulating JavaScript dates in a browser & Node.js. ?? Documentation

date-fns 30.6k Dec 29, 2022
:clock8: :hourglass: timeago.js is a tiny(2.0 kb) library used to format date with `*** time ago` statement.

timeago.js timeago.js is a nano library(less than 2 kb) used to format datetime with *** time ago statement. eg: '3 hours ago'. i18n supported. Time a

hustcc 4.9k Jan 4, 2023
A tiny and fast zero-dependency date-picker built with vanilla Javascript and CSS.

A tiny zero-dependency and framework-agnostic date picker that is incredibly easy to use! Compatible with any web UI framework, vanilla JS projects, and even HTML-only projects!

Nezar 1 Jan 22, 2021
Tiny millisecond conversion utility

ms Use this package to easily convert various time formats to milliseconds. Examples ms('2 days') // 172800000 ms('1d') // 86400000 ms('10h')

Vercel 4.4k Jan 4, 2023
:rainbow: Javascript color conversion and manipulation library

color JavaScript library for immutable color conversion and manipulation with support for CSS color strings. var color = Color('#7743CE').alpha(0.5).l

Qix 4.5k Jan 3, 2023
Fast, small color manipulation and conversion for JavaScript

TinyColor JavaScript color tooling TinyColor is a small, fast library for color manipulation and conversion in JavaScript. It allows many forms of inp

Brian Grinstead 4.5k Jan 1, 2023
Increase your landing page conversion rates.

Ouibounce Originally created by Carl Sednaoui from MailCharts. Maintained and improved by generous contributors. Ouibounce: A small library enabling y

Carl Sednaoui 2.3k Dec 9, 2022
A simple package for single or batch image download and conversion using node streams.

image-batch-download A simple package for basic image downloading and processing. Supported formats: JPEG PNG WebP Installation With Yarn: yarn add im

Tech Root 777 5 Jan 2, 2022
Colormath.js - a color conversion and color manipulation library written in typescript for Node.js, Deno and Browser

Colormath.js - a color conversion and color manipulation library written in typescript for Node.js, Deno and Browser

TheSudarsanDev 8 Feb 8, 2022
A NodeJS package to convert any RGB color to HEX color or viceversa. Also supports HSL conversion.

Unhex ?? A NodeJS package to convert any RGB color to HEX, HSL color or viceversa. Example div { color: #fff; background-color: #0070f3; } After r

Arnau Espin 2 Oct 1, 2022
A utility for creating toggleable items with JavaScript. Inspired by bootstrap's toggle utility. Implemented in vanillaJS in a functional style.

LUX TOGGLE Demo: https://jesschampion.github.io/lux-toggle/ A utility for creating toggleable dom elements with JavaScript. Inspired by bootstrap's to

Jess Champion 2 Oct 3, 2020
A tiny JavaScript utility to access deep properties using a path (for Node and the Browser)

object-path Access deep properties using a path Changelog 0.11.5 SECURITY FIX. Fix a prototype pollution vulnerability in the set() function when usin

Mario Casciaro 1k Dec 29, 2022
A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers

debug A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. Installation $ npm ins

Sloth 10.5k Dec 30, 2022
A tiny utility to asynchronously drive a namespace exposed through a Worker.

proxied-worker Social Media Photo by Ricardo Gomez Angel on Unsplash A tiny utility to asynchronously drive a namespace exposed through a Shared/Servi

Andrea Giammarchi 43 Dec 8, 2022
A tiny (304B to 489B) utility to check for deep equality

dequal A tiny (304B to 489B) utility to check for deep equality This module supports comparison of all types, including Function, RegExp, Date, Set, M

Luke Edwards 1.1k Dec 14, 2022
Tiny and fast utility to extract all possible values for a given enum.

Tiny (208B) and fast utility to extract all possible values for a given enum.

Andrea Cappuccio 2 Apr 18, 2022
A tiny, plugin extendable JavaScript utility library with a JQuery-like syntax.

Tiny Friggin' Utility Zapper What is it? A tiny ~7kb extendable JavaScript utility library with a JQuery like syntax for getting work done fast! If yo

Bret 4 Jun 25, 2022
A tiny utility library to generate mesh gradient based on 4 RGB colors, built with vanilla js.

MeshGradient.js mesh-gradient.js is tiny utility library to generate mesh gradient based on 4 RGB colors, built with vanilla js. Installation! npm ins

Anup Aglawe 7 Jan 4, 2023
A utility-first CSS framework for rapid UI development.

A utility-first CSS framework for rapidly building custom user interfaces. Documentation For full documentation, visit tailwindcss.com. Community For

Tailwind Labs 63.5k Dec 30, 2022
Low-level CSS Toolkit – the original Functional/Utility/Atomic CSS library

Basscss Low-level CSS toolkit – the original Functional CSS library https://basscss.com Lightning-Fast Modular CSS with No Side Effects Basscss is a l

Basscss 5.8k Dec 31, 2022