time-speak: A Node.JS Library For Parsing Dates and Durations ๐Ÿš€๐Ÿ•’


2 min read

Table of contents

Get time-speak here on npm

While working on track-time-cli, I encountered the need for a library to parse dates and intervals, so natural language could be used to specify time sheet entry start & end dates. For example, tt in --at 'three hours ago' some task

I went ahead and wrote a tiny library for this, time-speak. It is nearly dependency-free, with just one requirement of numbers-from-words, another zero-dependency library of mine for parsing numbers from words (i.e. parse('twenty three')).


To use, install it with npm i --save time-speak and import the parse method with either import { parse } from 'time-speak' or import parse from 'time-speak', then just pass the parse method your input string.

Thanks to numbers-from-words, number words are supported in the input, so all of the following are valid inputs:

  • "2 days and three hours ago"

  • "in five weeks"

  • "3 minutes ago"

  • "24 hours"

Inputs specifying a date in the future (starting with "in") are parsed as such, while inputs ending in "ago" are parsed as dates in the past, relative to the present moment. Such inputs to parse return Date objects.

Inputs without the "in" prefix or "ago" suffix are parsed as durations, and the return value is the duration length in milliseconds, a number.

Here is an example taken from the docs:

import { parse } from 'time-speak'

const pastDate = parse('2 days and 4 hours ago')
const pastDateWithNumberWords = parse('two days and four hours ago')
const futureDate = parse('in 4 hours')
const durationMS = parse('6 months')

  pastDateWithNumberWords,    // 2023-12-19T13:02:39.768Z
  pastDate,                   // 2023-12-19T13:02:39.768Z
  futureDate,                 // 2023-12-21T21:02:39.768Z
  durationMS                  // 15552000000

That's it! Go ahead and start hacking!