DEV Community

Cover image for time-speak: A Node.JS Library For Parsing Dates and Durations πŸš€πŸ•’
Cris Mihalache
Cris Mihalache

Posted on

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

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')).


Usage

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

console.log({
  pastDateWithNumberWords,    // 2023-12-19T13:02:39.768Z
  pastDate,                   // 2023-12-19T13:02:39.768Z
  futureDate,                 // 2023-12-21T21:02:39.768Z
  durationMS                  // 15552000000
})
Enter fullscreen mode Exit fullscreen mode

That's it! Go ahead and start hacking!

Links:

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❀️