Coder Social home page Coder Social logo

timestring's Introduction

timestring

Version Build Status Coveralls npm License

Parse a human readable time string into a time based value.

Installation

npm install --save timestring

Usage

Overview

const timestring = require('timestring')

let str = '1h 15m'
let time = timestring(str)

console.log(time) // will log 4500

By default the returned time value from timestring will be in seconds.

The time string can contain as many time groups as needed:

const timestring = require('timestring')

let str = '1d 3h 25m 18s'
let time = timestring(str)

console.log(time) // will log 98718

and can be as messy as you like:

const timestring = require('timestring')

let str = '1 d    3HOurS 25              min         1   8s'
let time = timestring(str)

console.log(time) // will log 98718

Keywords

timestring will parse the following keywords into time values:

  1. ms, milli, millisecond, milliseconds - will parse to milliseconds
  2. s, sec, secs, second, seconds - will parse to seconds
  3. m, min, mins, minute, minutes - will parse to minutes
  4. h, hr, hrs, hour, hours - will parse to hours
  5. d, day, days - will parse to days
  6. w, week, weeks - will parse to weeks
  7. mon, mth, mths, month, months - will parse to months
  8. y, yr, yrs, year, years - will parse to years

Keywords can be used interchangeably:

const timestring = require('timestring')

let str = '1day 15h 20minutes 15s'
let time = timestring(str)

console.log(time) // will log 141615

Return Time Value

By default the return time value will be in seconds. This can be changed by passing one of the following strings as an argument to timestring:

  1. ms - Milliseconds
  2. s - Seconds
  3. m - Minutes
  4. h - Hours
  5. d - Days
  6. w - Weeks
  7. mth - Months
  8. y - Years
const timestring = require('timestring')

let str = '22h 16m'

let hours = timestring(str, 'h')
let days = timestring(str, 'd')
let weeks = timestring(str, 'w')

console.log(hours) // will log 22.266666666666666
console.log(days) // will log 0.9277777777777778
console.log(weeks) // will log 0.13253968253968254

Optional Configuration

A few assumptions are made by default:

  1. There are 24 hours per day
  2. There are 7 days per week
  3. There are 4 weeks per month
  4. There are 12 months per year
  5. There are 365.25 days per year

These options can be changed by passing an options object as an argument to timestring.

The following options are configurable:

  1. hoursPerDay
  2. daysPerWeek
  3. weeksPerMonth
  4. monthsPerYear
  5. daysPerYear
const timestring = require('timestring')

let str = '1d'
let opts = {
  hoursPerDay: 1
}

let time = timestring(str, 'h', opts)

console.log(time) // will log 1

In the example above hoursPerDay is being set to 1. When the time string is being parsed, the return value is being specified as hours. Normally 1d would parse to 24 hours (as by default there are 24 hours in a day) but because hoursPerDay has been set to 1, 1d will now only parse to 1 hour.

This would be useful for specific application needs.

Example - Employees of my company work 7.5 hours a day, and only work 5 days a week. In my time tracking app, when they type 1d i want 7.5 hours to be tracked. When they type 1w i want 5 days to be tracked etc.

const timestring = require('timestring')

let opts = {
  hoursPerDay: 7.5,
  daysPerWeek: 5
}

let hoursToday = timestring('1d', 'h', opts)
let daysThisWeek = timestring('1w', 'd', opts)

console.log(hoursToday) // will log 7.5
console.log(daysThisWeek) // will log 5

It is important to note that the daysPerYear configuration option will be used to convert a month or year to seconds, so if you are using custom configuration options make sure that you adjust this value to suit if you expect to be parsing timestrings containing months or years.

Notes

If the string that is passed into timestring can not be parsed then an error will be thrown:

const timestring = require('timestring')

let str = 'aaabbbccc'
let time = timestring(str) // will throw an error

If a number is passed into timestring it will be treated as a string containing milliseconds:

const timestring = require('timestring')

let time = timestring(3000) // 3s

timestring's People

Contributors

alexeymarunin avatar cvan avatar dependabot-preview[bot] avatar dependabot[bot] avatar floneu avatar greenkeeper[bot] avatar greenkeeperio-bot avatar ianmitchell avatar mike182uk avatar mrbar42 avatar vegeta897 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

Watchers

 avatar  avatar  avatar  avatar  avatar

timestring's Issues

Unsafe use of "for each"?

Hi, Mike! Thanks for your create project.
I ran into some issues with your code using it in an angular project. The strange think is i wrote unit tests for the methode depending on timestring und everything worked fine in testing environment. When i ran the method in development project exceptions were thrown ( '3s'.parseTime()

TypeError: undefined is not a function.
I tracked that to this
for(var group in groups) { var g = groups[group], value = g.match(/[0-9]+/g)[0], unit = g.match(/[a-z]+/g)[0]; totalSeconds += getSeconds(value, unit); }
I don't know why this worked in testing, but it seems for each isn't really the best way to access array-elements, because methods on the array like 'concat' are also valid keys, which then break the code. I fixed this simply by using a normal for-loop with index.

Correct convert numbers

I think it can be useful don't throw exception for numbers (treating them as ms)

const timestring = require('timestring')
const minutes = timestring(300000, 'm')
console.log(minutes) // 5

Should throw error if the given string is not even a timestring

I observe that there is already a test case for timestring having unrecognized time unit at:

it('throws an error when an invalid unit is used in the timestring', () => {

However, the lib should do the same if the entire given string is not a timestring at all.

For now (release 5.0.0):

  • timestring('test', 'milliseconds') => 0
  • timestring('0test', 'milliseconds') => Error: The unit [test] is not supported by timestring

Months being returned as minutes for unit `m`

>> ts.parse('1 month', 'm')
1
>> ts.parse('1 minute', 'm')
1
>> ts.parse('1 month', 'mth')
0.0000248015873015873
>> ts.parse('1 minute', 'mth')
0.0000248015873015873

It looks like when we're returning months as minutes when the unit is m.

Seconds per year is not correct

The result for a year, e.g. of

console.log(timestring("1y"));

is 29030400

but a year has 31,536,000 seconds.

This is also wrong in the tests!
I think, it comes from the wrong calculation, which uses "monthsPerYear * weeksPerMonth" and weeksPerMonth is 4.

Is this intended, or would it be better to use e.g. an additonal "daysPerYear" option?

Seconds per month is not correct

By default:

  1. There are 7 days per week
  2. There are 4 weeks per month

So there are 28 days per month.

Seconds per month = 28 * 24 * 60 * 60 = 2419200

However

const timestring = require('timestring');

let time = timestring('1mon');
console.log(time);
// print 2629800

and 2629800 is 30.4375 days.

Inconsistant return values and '10m s' error

Hi, Mike! Another thing i want to mention, because i ran into it while writing the test for integrating your timestring-module into my application... First of all i tested some timestrings, then omitting the second number. What now happens is that timestring parses this as 'ms' or 'sm'-unit throwing 'Unsupported unit'-Error.

; TimeDateHandler.GetTimeInMS( '1m s' ) or TimeDateHandler.GetTimeInMS( '1s m' )

Also for this random strings, different negatives are returned. For a string
that doesn't contain a numeric value 0 is returned ( also if there is no possible unit contained )....

; expect( TimeDateHandler.GetTimeInMS( 'lalalasursursumsum') ).toBe( 0 )
; expect( TimeDateHandler.GetTimeInMS( 'aaaaaa') ).toBe( 0 )

while containing false, if numeric value is contained.

; expect( TimeDateHandler.GetTimeInMS( 'lal10sumsum') ).toBe( false )

What are your thoughts on this... g

Support for Negative Strings

I was wondering if you would accept a pull request which adds support for negative numbers?

str = "-1d";
inSeconds = str.parseTime();
console.log(inSeconds); // logs -86400 instead of 86400 as per current implementation

I'm not yet sure how we would handle cases like:

str = "1d -10m";
inSeconds = str.parseTime();
// may be this logs -85800 ?

Thoughts?

An in-range update of coveralls is breaking the build 🚨

The devDependency coveralls was updated from 3.0.2 to 3.0.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

coveralls is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).
  • βœ… coverage/coveralls: First build on greenkeeper/coveralls-3.0.3 at 100.0% (Details).

Release Notes for Dependency security updates

As suggested by NPM and Snyk.

Commits

The new version differs by 1 commits.

  • aa2519c dependency security audit fixes from npm & snyk (#210)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

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.