@diatche/parse-time

A utility for parsing time duration and time of the day strings.

Usage no npm install needed!

<script type="module">
  import diatcheParseTime from 'https://cdn.skypack.dev/@diatche/parse-time';
</script>

README

@diatche/parse-time

Node.js CI

A utility for parsing time duration and time of the day strings.

No external dependencies.

Installation

yarn add @diatche/parse-time

Or with npm:

npm install --save @diatche/parse-time

Usage

The main method parseTime() (timeParse() is an alias) parses human input time values into an object containing the hours, minutes and total milliseconds from the start of the day.

import { parseTime } from 'parse-time';
const lunchtime = parseTime('12:30 pm');
const { hours, minutes, totalMs } = lunchtime;

You can also compare the returned object directly (as total milliseconds from the start of the day), thanks to valueOf() method implementation.

const time = new Date('2021-06-03T12:31:00.000Z') % 86400000;
console.log('is it time for lunch?: ' + (time > lunchtime));

To limit the time to a specific amount, use the max option:

let invalidTime = parseTime('25:00', { max: 86400e3 });
assert(typeof invalidTime === 'undefined');

Or use the parseTimeOfDay() method to limit the time to 24 hours. This is useful when parsing the date and time separately.

import { parseTimeOfDay } from 'parse-time';
const { hours, minutes, totalMs } = parseTimeOfDay('09:00');

Parsed Formats

Multiple input formats are supported. Have a look at the unit tests for a comprehensive list.