Giter VIP home page Giter VIP logo

ms's Introduction

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 vaues.
    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

ms's People

Contributors

artskydj avatar ballomud avatar binki avatar dependabot[bot] avatar esrefdurna avatar getsnoopy avatar gobwas avatar greenkeeper[bot] avatar greenkeeperio-bot avatar jfmengels avatar juliangruber avatar kaisugi avatar karenyavine avatar khmm12 avatar knpwrs avatar leerob avatar leo avatar leoiannacone avatar mrmckeb avatar msmolens avatar nathankleyn avatar rauchg avatar shime avatar styfle avatar swatinem avatar tj avatar tubalmartin avatar wizek avatar yoavmmn avatar yuler avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ms's Issues

90 minutes is rounded up to 2 hours

When providing the ms function with the number 5400000, it's returning 2h, or 2 hours if verbose is true. This is not the desired behavior, as 5400000 ms is 90 minutes, or 1,5 hours

Doesn't support more then 24 days?

I added ms into my Discord bot but ms seems to only support up to 24 days otherwhise it will set the timer automaticly to 0. Is this a bug from the current build? (I installed the latest npm build)

Example Code:

const ms = require("ms"); 
setTimeout(async function(){
     console.log("Timer finished")
}, ms(mutetime));

(I set the time/value for ms with a discord command - this works as it should with for example 10s or 7d however would I like to be able to do 1y or maybe -1 so it will never stop)

Question

Can you do something like this 1h 2s to make it into ms?

Unexpected behavior when parsing a human-readable expression

Use-Case Overview

I added ms to let Ops configure some intervals on their ~/config/local.yaml in a human-readable fashion.

The ops tried:

app:
   interval: 1h 30min

This evidently did not behave as expected.

Reproduction steps:

const ms = require('ms');
const v = ms('1h 30min')
console.log(v)

expected behavior

5400000

found behavior

undefined

Support singular form without integer

Now I can use multiple ways to get number of milliseconds for singular forms of string:

ms('1h') // 3600000
ms('1 h') // 3600000
ms('1hour') // 3600000
ms('1 hour') // 3600000
ms('1hours') // 3600000
ms('1 hours') // 3600000
// ...

But I can't do in the following way without integer:

ms('h') // undefined, should be 3600000
ms('hour') // undefined, should be 3600000

Question

Hello I was curious if you could so stuff like 1m5s to ms

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

Fix YUI compression (redux)

According to Mocha's changelog, PR #53 didn't finish the job.

mochajs/mocha#1035

This wasn't fully fixed. Having options.long still causes YUI to fail.

-  return options.long ? fmtLong(val) : fmtShort(val);
+  return options['long'] ? fmtLong(val) : fmtShort(val);

There is only partial support for negative time

Support for negative time was recently added but it doesn't work for all cases.

Expected Behavior

ms(-1 * 60 * 1000, { long: true }) => -1 minute
ms(-1 * 60 * 60 * 10000, { long: true }) => -10 hours
ms(-234234234, { long: true }) => -3 days

Actual Behavior

ms(-1 * 60 * 1000, { long: true }) => -60000 ms
ms(-1 * 60 * 60 * 10000, { long: true }) => -36000000 ms
ms(-234234234, { long: true }) => -234234234 ms

Support for decimal place display

Instead of always round to integer, if it can round to certain decimal place it will be great!

For example:

ms(60000, {decimal: 1 })                            // "1m"
ms(66000, {decimal: 1 })                            // "1.1m"
ms(-3 * 66000, { long: true, decimal: 1 })          // "-3.3 minutes"
ms(234234234, { decimal: 2  })                      // "2.71m"
ms(ms('10.5 hours'), { long: true, decimal: 1 })    // "10.5 hours"

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?

Please add license to package.json

Your package is listed as "unknown" by automatic license checkers because your package.json does not have a license field. It would be very handy if you could add it.

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?

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

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.

Wrong time returned when using `{ long: true }`

Consider the following

> t = 21600001
21600001
> ms(t)
'6h'
> ms(t, { long: true })
'7 hours'

and note that ms returned a different time value with { long: true } options

> h = t / 1000 / 60 / 60 // hours
6.000000277777778
> Math.ceil(h)
7

which is the result if something like Math.ceil were used in the conversion.

tl;dr

When given a number that cannot be divided evenly in to a unit of time (e.g. 21600001 ) and { long: true }, ms returns the wrong time.

Where n = 21600001 / 1000 / 60 / 60
expected: ${n} hours
actual: ${n + 1} hours

EDIT:
I'm using version 2.0.0

Conversions from milliseconds are rounded

ms("2.5 hrs") // 9000000
ms("9000000") // 3h
ms("9000000", { long: true ) // 3 hours

The above code returns "3h" or "3 hours" when a total of 2.5 hrs in milliseconds is parsed.

If there are technical limitations to returning accurate string representations, it would be ideal to provide an example and explanation in the repository readme.md.

Software license

Hi,

do you think it´s possible to add a license header somewhere in this project. The reason why I need this, is because I´m introducing the mocha test framework at our company and ms.js is a dependency with mocha.

Would appreciate it!

Thanks a lot,

Alex

component.json file out of date

Everything else declares this as version 0.7.0, except the component.json file, which is still at 0.6.1

Also the repo is still the old name in the component.json file.

Please include a license

Hi there. It would be really helpful from a distribution packaging point of view if you could include a copy of the MIT license text with your software, usually in a file called LICENSE.

Thanks!

Release

Can we have a new release so we stop getting "there's no repository field" warnings?

Should ms handle 9h30 and 3m50s ?

#55, #102, #25 was pull request for that, #54, #24, #110 are open issues for that.

the pull request have been closed without merging, and the issues are still opened.

Is there a lack of something in the pull request, and i shoud write one with all quality test requered for the pull request to be merged ?
Or shoud the issues #54, #24, #110 should be closed with the wontfix flag ? (and an other project like https://github.com/Cat66000/ms-i18n/issues/2 should implement it ? )

License file?

Would it be possible to include a LICENSE file with the text of the license agreement?
Our lawyers are saying that just having "License: MIT" is not sufficient.

parse() should throw instead of returning undefined

What's the reasoning behind parse() returning undefined when given invalid input (e.g. '1 secnd')? In my opinion, an error will be much easier to detect and feels syntactically more appropriate – passing an invalid string is an erroneous usage of the function, after all.

I'd totally be willing to draft a PR if there's agreement an error should be thrown.

"1 week" returns undefined

I would expect "1 week" to return a result.

> ~/Projects/voxmedia/tempo $ npm install ms
[email protected] node_modules/ms
~/Projects/voxmedia/tempo $ node
> var ms = require('ms')
undefined
> ms('5 minutes')
300000
> ms('15 minutes')
900000
> ms('2 hours')
7200000
> ms('2 hour')
7200000
> ms('2 h')
7200000
> ms('1 day')
86400000
> ms('1 week')
undefined
> ms('1 weeks')
undefined
> ms('1 month')
undefined
> ms('1 year')
31557600000

I would also expect "1 month" to return a result (though that one is slightly tricky) and sources seem to disagree.

month

^ I would probably just call it 30 days even and be done with it. Maybe include a note in the docs as to what the library considers 1 month.

Anyhow, weeks should probably work. Otherwise the lib is great. Thanks!

NPM BREAKING BUG => `ms` module breaks build

Version 0.7.1 Is breaking NPM builds, due to some bad characters, package.json is below

screen shot 2015-11-18 at 4 36 43 pm

screen shot 2015-11-18 at 4 37 30 pm

{
"name": "ms",
"version": "0.7.1",
"description": "Tiny ms conversion utility",
"repository": {
"type": "git",
"url": "git://github.com/guille/ms.js.git"
},
"main": "./index",
"devDependencies": {
"mocha": "",
"expect.js": "
",
"serve": "*"
},
"component": {
"scripts": {
"ms/index.js": "index.js"
}
},
"gitHead": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909",
"bugs": {
"url": "https://github.com/guille/ms.js/issues"
},
"homepage": "https://github.com/guille/ms.js",
"_id": "[email protected]",
"scripts": {},
"_shasum": "9cd13c03adbff25b65effde7ce864ee952017098",
"_from": "[email protected]",
"_npmVersion": "2.7.5",
"_nodeVersion": "0.12.2",
"_npmUser": {
"name": "rauchg",
"email": "[email protected]"
},
"maintainers": [
{
"name": "rauchg",
"email": "[email protected]"
}
],
"dist": {
"shasum": "9cd13c03adbff25b65effde7ce864ee952017098",
"tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz"
}

How to save the time?

Hello I would have a question that there is a command say the mute command I use this module but I recently started dealing with sqlite3 module and I would have a question how I could save the values ​​so let's put it in 3 minutes but in between do i stop the stick and then restart it as long as the number went save it? and load?

Throw more precise error when given bad input

In exported function here, be more precise about thrown type.

function(val, options) {
  options = options || {};
  var err;
  var type = typeof val;

  if (type === 'string' && val.length > 0) {
    return parse(val);
  } else if (type === 'number' && isNaN(val) === false) {
    return options['long'] ? fmtLong(val) : fmtShort(val);
  } else {
    var err;
    var message;
    var code;

    if (type === 'string' || type === 'number') {
      message = 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val);
      code = 'ERR_INVALID_ARG_VALUE';  
    } else {
      message = 'val must be string or number, not ' + type;
      code = 'ERR_INVALID_ARG_TYPE';  
    }
    err = new TypeError(message);
    err.code = code;  
    throw err;
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.