haversnail / inquirer-date-prompt

A date prompt plugin for Inquirer.js.
https://www.npmjs.com/package/inquirer-date-prompt
MIT License
19 stars 2 forks source link
date datetime datetimepicker inquirer locale picker plugin prompt time
Inquirer Logo

inquirer-date-prompt

A comprehensive date prompt plugin for Inquirer.js.

Why?

Installation

npm install inquirer-date-prompt

:warning: Note that the latest version of this package uses native ES modules, which means this plugin will only work with inquirer v9 and above. If you cannot use ES modules yet for whatever reason, you can rely on v2.x until you're ready to upgrade your environment:

npm install --save inquirer-date-prompt@^2.0.0

Usage

import inquirer from "inquirer";
import DatePrompt from "inquirer-date-prompt";

inquirer.registerPrompt("date", DatePrompt);

inquirer.prompt({
  type: "date",
  // ...
});

Although you can use whatever type name you want, registering the prompt with a type of 'date' will afford you IntelliSense when specifying the prompt options, thanks to TypeScript's declaration merging.

Prompt

To change the date, simply use the left and right arrow keys to move the cursor, and up and down to change the value. You can also use modifier keys to determine by how much to increase or decrease the value:

Demo

Options

Note: allowed options written inside square brackets ([]) are optional. Others are required.

type, name, message [, default, filter, validate, transformer, locale, format, clearable]

default (Date)

transformer (Function)

locale 1 (String | Array\<String>)

Demo

format (Intl.DateTimeFormatOptions)

clearable (Boolean)

See the inquirer README for details on all other options.

Example

async function getTimestamp(date) {
  const { timestamp } = await inquirer.prompt({
    type: "date",
    name: "timestamp",
    message: "When will the world end?",
    prefix: " 🌎 ",
    default: date,
    filter: (d) => Math.floor(d.getTime() / 1000),
    validate: (t) => t * 1000 > Date.now() + 86400000 || "God I hope not!",
    transformer: (s) => chalk.bold.red(s),
    locale: "en-US",
    format: { month: "short", hour: undefined, minute: undefined },
    clearable: true,
  });
  return timestamp;
}

Demo

Caveats

  1. Be aware that even though this plugin works with Node ≥ v12, specifying a locale other than 'en-US' while running on any version less than 13.0.0 will fail silently. See the MDN docs for more details.