Meet Flatpickr

The last datetime picker you'll ever need.

Getting Started

npm install flatpickr
bower install flatpickr-calendar

Flatpickr in browsers

<link rel="stylesheet" href=".../flatpickr.min.css">
<script src=".../flatpickr.min.js"></script>

The latest version of Flatpickr can also be loaded from a CDN

<link rel="stylesheet" href="https://unpkg.com/flatpickr/dist/flatpickr.min.css">
<script src="https://unpkg.com/flatpickr"></script>

Then,

flatpickr(".selector", {}); // [Flatpickr, Flatpickr, ...]
document.getElementById("myID").flatpickr(config); // Flatpickr
let calendar = new Flatpickr(element, config); // Flatpickr


$(".selector").flatpickr({}); // jQuery

Flatpickr as a module

const Flatpickr = require("flatpickr");
// ...
new Flatpickr(element, config);

Examples

Basic

<input class="flatpickr" type="text" placeholder="Select Date..">
flatpickr(".flatpickr");

Make it a datetime picker

flatpickr(".flatpickr", {
    enableTime: true
});

Display a human-readable date

flatpickr(".flatpickr", {
    enableTime: true,

    // create an extra input solely for display purposes
    altInput: true,
    altFormat: "F j, Y h:i K"
});

Limit the range of available dates with minDateand maxDate

minDate and maxDate accept Date objects, date strings, timestamps, and the shortcut "today"

flatpickr(".flatpickr", {
    minDate: new Date(), // "today" / "2016-12-20" / 1477673788975
    maxDate: "2016-12-20",
    enableTime: true,

    // create an extra input solely for display purposes
    altInput: true,
    altFormat: "F j, Y h:i K"
});

Preloading Dates

Flatpickr can work with existing date strings, or date objects.

Input values get parsed automatically.

<input type="text", value="2016-10-20">

To preload a Date object, timestamp, or otherwise supply a date string, use thedefaultDate option.

Timestamps are recommended due to their lack of ambiguity in parsing.

flatpickr("#example-defaultDate", {
    defaultDate: 1477697199863, // Date objects and date strings are also accepted
    enableTime: true
});


UTC mode

By default, all dates in javascript are converted to a local time. However, you can choose to leave the dates in UTC. flatpickr can convert any given dates to UTC and select a datetime in UTC with a simple switch.

flatpickr("#utc", {
    utc: true,
    defaultDate: "2016-12-27T16:16:22.585Z",
    enableTime: true,
});

Custom elements and input groups

flatpickr can parse an input group of textboxes and buttons, common in Bootstrap and other frameworks.

This permits additional markup, as well as custom elements to trigger the state of the calendar.

Mark your input element withdata-input(mandatory), and any additional buttons withdata-toggle,data-open,data-close, ordata-clear.

<p class="flatpickr">
    <input placeholder="Pick date" data-input>

    <a class="input-button" data-toggle><i class="icon-calendar"></i></a>
    <a class="input-button" data-clear><i class="icon-close"></i></a>
</p>
flatpickr(".flatpickr", {
    wrap: true,
    clickOpens: false // disable opening calendar by clicking on input
});

Disabling dates

Disable a date interval, or a specific date.

document.getElementById("#disableRange").flatpickr({
    disable: [
        { from: "2016-08-16", to: "2016-08-19" },
        "2016-08-24",
        new Date().fp_incr(30) // 30 days from now
    ]
});

Boolean functions are also supported. This allows fine-grained control over every single date, flexible enough for any use-case.

document.getElementById("#disableOddDays").flatpickr({
    disable: [
        function(date){ // disable odd days
            return date.getDate()%2 > 0;
        }
    ]
});

Enabling dates

Use the enable[] option to disable all dates except the ones you specify.

Similar to disable[], accepts date strings, intervals, Date objects, or functions.

document.getElementById("#enableNextSeven").flatpickr({
    enable: [
        {
            from: "today",
            to: new Date().fp_incr(7) // 7 days from now
        }
    ]
});

For instance, to enable only business days of 2016:

document.getElementById("#enableCustom").flatpickr({
    enable: [
        function(dateObj){
            // dateObj is a JavaScript Date
            return dateObj.getDay() %6 !== 0 && dateObj.getFullYear() === 2016;
        }
    ]
});

Inline Calendar

flatpickr("#inline", {
    inline: true, // show the calendar inline
    weekNumbers: true // show week numbers
})

Fiscal Calendar

You may override thegetWeek()function, used for calculating a week number, for various purposes. A fiscal year is used for calculating yearly financial statements. In this example, we will use override thegetWeek()function to display the fiscal term instead of the usual week numbers.

<input type='text' id="fiscal" placeholder="Fiscal Calendar">
document.getElementById("fiscal").flatpickr({
    weekNumbers: true,
    getWeek: function(givenDate){
        var checkDate = new Date(givenDate.getTime());
        checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
        var time = checkDate.getTime();
        checkDate.setMonth(7);
        checkDate.setDate(28);

        var week = (Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 2);
        if (week < 1) {
            week = 52 + week;
        }

        return 'FW' + ("0" + week).slice(-2);
    }
});


Events

Flatpickr has 5 event hooks for the most common and useful actions. For each hook, you may specify a single function, or an array of functions. Callback arguments are explained below.

selectedDates is an array of Date objects selected by the user. When there are no dates selected, the array is empty.

dateStr is a string representation of the latest selected Date object by the user. The string is formatted as per thedateFormatoption.

instance is the Flatpickr object, containing various methods and properties.

Hooks

onChange

onChange gets triggered when the user selects a date, or changes the time on a selected date.

onOpen

onOpen gets triggered when the calendar is opened.

onClose

onClose gets triggered when the calendar is closed.

document.getElementById("events-api-example").flatpickr({
    onChange: function(selectedDates, dateStr, instance) {
        ...
    },
    onOpen: function(selectedDates, dateStr, instance){
        ...
    },
    onClose: function(selectedDates, dateStr, instance){
        ...
    }
});


onReady

onReady gets triggered once the calendar is in a ready state.

onValueUpdate

onValueUpdate gets triggered when the input value is updated with a new date string.

onDayCreate()

Take full control of every date cell with theonDayCreate()hook.

flatpickr("#dayCreate", {
    onDayCreate: function(dObj, dStr, fp, dayElem){
        // utilize fp.currentYear, fp.currentMonth, dayElem.textContent
        if (Math.random() < 0.15)
            dayElem.innerHTML += "<span class='event'></span>";

        else if (Math.random() > 0.85)
            dayElem.innerHTML += "<span class='event busy'></span>";
    }
});


API

These methods are exposed on every Flatpickr instance, letting you control the calendar programmatically.

changeMonth(monthNum, is_offset = true)

Changes the current month.

let calendar = new Flatpickr(yourElement, config);
calendar.changeMonth(1); // go a month ahead
calendar.changeMonth(-2); // go two months back

calendar.changeMonth(0, false); // go to January

clear()

Resets the selected dates (if any) and clears the input.

close()

Closes the calendar.

destroy()

Destroys the Flatpickr instance, cleans up - removes event listeners, restores inputs, etc.

formatDate(formatStr, dateObj)

formatStr  is a string consisting of formatting tokens, and dateObj  is a Date.

Return Value

A string representation ofdateObj,  formatted as per formatStr

jumpToDate(date)

Sets the calendar view to the year and month ofdate, which can be a date string, a Date, or nothing.

Ifdateis undefined, the view is set to the latest selected date, the minDate, or today's date

open()

Shows/opens the calendar.

parseDate(date)

Parses a date string or a timestamp, and returns a Date.

redraw()

Redraws the calendar. Shouldn't be necessary in most cases.

set(option, value)

Sets a config option optionto value, redrawing the calendar and updating the current view, if necessary.

setDate(date)

Sets the current selected date(s) todate, which can be a date string, a Date, or anArray of the aforementioned

toggle()

Shows/opens the calendar if its closed, hides/closes it otherwise

Options

Protip:all of the string/boolean config options can also be supplied using data attributes, e.g. data-min-date, data-default-date, data-date-format etc.

Config OptionTypeDefaultDescription
altFormatstring"F j, Y"Exactly the same as date format, but for the altInput field
altInputBooleanfalseShow the user a readable date (as per altFormat), but return something totally different to the server.
altInputClassString""This class will be added to the input element created by the altInput option. Helpful if input elements are styled using classes. Bootstrap users will want to specifyform-controlhere.
allowInputbooleanfalseAllows the user to enter a date directly input the input field. By default, direct entry is disabled.
clickOpensbooleantrueClicking on the input opens the date (time) picker. Disable this if you wish to open the calendar manually with.open()
dateFormatstring"Y-m-d"A string of characters which are used to define how the date will be displayed in the input box. The supported characters are defined in the table below.
defaultDateString/DatenullSet the initial selected date. Same as preloading a date string into an input's value attribute, but can also handle a Date object.
disablearray[]See Disabling dates
enablearray[]See Enabling dates
enableTimebooleanfalseEnables time picker
enableSecondsbooleanfalseEnables seconds in the time picker.
hourIncrementinteger1Adjusts the step for the hour input (incl. scrolling)
inlinebooleanfalseDisplays the calendar inline
maxDateString/DatenullThe maximum date that a user can pick to.
minDateString/DatenullThe minimum date that a user can start picking from.
minuteIncrementinteger5Adjusts the step for the minute input (incl. scrolling)
nextArrowstring>Code for the arrow icon, used to switch months.
noCalendarbooleanfalseHides the calendar. For use along with enableTime.
onChangefunction, [functions]nullFunction(s) to trigger on every date selection. See Events API
onClosefunction, [functions]nullFunction(s) to trigger on every time the calendar is closed. See Events API
onOpenfunction, [functions]nullFunction(s) to trigger on every time the calendar is opened. See Events API
onReadyfunction, [functions]nullFunction to trigger when the calendar is ready. See Events API
parseDatefunctionfalseFunction that expects a date string and must return a Date object
prevArrowstring<Code for the left arrow icon.
shorthandCurrentMonthbooleanfalseShow the month using the shorthand version (ie, Sep instead of September).
staticbooleanfalsePosition the calendar inside the wrapper and next to the input element. (Leavefalseunless you know what you're doing.
time_24hrbooleanfalseDisplays time picker in 24 hour mode without AM/PM selection when enabled.
utcbooleanfalseWhen true, dates will parsed, formatted, and displayed in UTC. It's recommended that date strings contain the timezone, but not necessary.
weekNumbersbooleanfalseEnables display of week numbers in calendar.
wrapBooleanfalseCustom elements and input groups

Date Format Characters

CharacterDescriptionExample
dDay of the month, 2 digits with leading zeros01 to 31
DA textual representation of a dayMon through Sun
l (lowercase 'L')A full textual representation of the day of the weekSunday through Saturday
jDay of the month without leading zeros1 to 31
JDay of the month without leading zeros and ordinal suffix1st, 2nd, to 31st
wNumeric representation of the day of the week0 (for Sunday) through 6 (for Saturday)
FA full textual representation of a monthJanuary through December
mNumeric representation of a month, with leading zero01 through 12
nNumeric representation of a month, without leading zeros1 through 12
MA short textual representation of a monthJan through Dec
UThe number of seconds since the Unix Epoch1413704993
yA two digit representation of a year99 or 03
YA full numeric representation of a year, 4 digits1999 or 2003

Time Format Characters

CharacterDescriptionExample
HHours (24 hours)00 to 23
hHours1 to 12
iMinutes00 to 59
SSeconds, 2 digits00 to 59
sSeconds0, 1 to 59
KAM/PMAM or PM

Escaping date format characters

To escape a character (if you need to use one of the reserved format characters above) use a double backslash:\\

Example:

\\D\\a\\y \\p\\i\\c\\k\\e\\d: Y/m/d

To get something like:

Day picked: 2013/02/12

If you do not escape the characters you would end up with something like this instead:

Tuea13 picke12: 2013/02/12

Which is probably not what you want...

Note: It's recommended that you escape all characters that you don't want accidentally converted to format characters in the future as others are added.