The last datetime picker you'll ever need.
npm install flatpickr
bower install flatpickr-calendar
<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
const Flatpickr = require("flatpickr");
// ...
new Flatpickr(element, config);
<input class="flatpickr" type="text" placeholder="Select Date..">
flatpickr(".flatpickr");
flatpickr(".flatpickr", {
enableTime: true
});
flatpickr(".flatpickr", {
enableTime: true,
// create an extra input solely for display purposes
altInput: true,
altFormat: "F j, Y h:i K"
});
minDate
and 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"
});
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.
flatpickr("#example-defaultDate", {
defaultDate: 1477697199863, // Date objects and date strings are also accepted
enableTime: true
});
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,
});
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
});
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;
}
]
});
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;
}
]
});
flatpickr("#inline", {
inline: true, // show the calendar inline
weekNumbers: true // show week numbers
})
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);
}
});
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 thedateFormat
option.
instance
is the Flatpickr object, containing various methods and properties.
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.
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>";
}
});
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.
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.
Ifdate
is 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 option
to 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
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 Option | Type | Default | Description |
---|---|---|---|
altFormat | string | "F j, Y" | Exactly the same as date format, but for the altInput field |
altInput | Boolean | false | Show the user a readable date (as per altFormat), but return something totally different to the server. |
altInputClass | String | "" | 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-control here. |
allowInput | boolean | false | Allows the user to enter a date directly input the input field. By default, direct entry is disabled. |
clickOpens | boolean | true | Clicking on the input opens the date (time) picker. Disable this if you wish to open the calendar manually with.open() |
dateFormat | string | "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. |
defaultDate | String/Date | null | Set the initial selected date. Same as preloading a date string into an input's value attribute, but can also handle a Date object. |
disable | array | [] | See Disabling dates |
enable | array | [] | See Enabling dates |
enableTime | boolean | false | Enables time picker |
enableSeconds | boolean | false | Enables seconds in the time picker. |
hourIncrement | integer | 1 | Adjusts the step for the hour input (incl. scrolling) |
inline | boolean | false | Displays the calendar inline |
maxDate | String/Date | null | The maximum date that a user can pick to. |
minDate | String/Date | null | The minimum date that a user can start picking from. |
minuteIncrement | integer | 5 | Adjusts the step for the minute input (incl. scrolling) |
nextArrow | string | > | Code for the arrow icon, used to switch months. |
noCalendar | boolean | false | Hides the calendar. For use along with enableTime. |
onChange | function, [functions] | null | Function(s) to trigger on every date selection. See Events API |
onClose | function, [functions] | null | Function(s) to trigger on every time the calendar is closed. See Events API |
onOpen | function, [functions] | null | Function(s) to trigger on every time the calendar is opened. See Events API |
onReady | function, [functions] | null | Function to trigger when the calendar is ready. See Events API |
parseDate | function | false | Function that expects a date string and must return a Date object |
prevArrow | string | < | Code for the left arrow icon. |
shorthandCurrentMonth | boolean | false | Show the month using the shorthand version (ie, Sep instead of September). |
static | boolean | false | Position the calendar inside the wrapper and next to the input element. (Leavefalse unless you know what you're doing. |
time_24hr | boolean | false | Displays time picker in 24 hour mode without AM/PM selection when enabled. |
utc | boolean | false | When true, dates will parsed, formatted, and displayed in UTC. It's recommended that date strings contain the timezone, but not necessary. |
weekNumbers | boolean | false | Enables display of week numbers in calendar. |
wrap | Boolean | false | Custom elements and input groups |
Character | Description | Example |
---|---|---|
d | Day of the month, 2 digits with leading zeros | 01 to 31 |
D | A textual representation of a day | Mon through Sun |
l (lowercase 'L') | A full textual representation of the day of the week | Sunday through Saturday |
j | Day of the month without leading zeros | 1 to 31 |
J | Day of the month without leading zeros and ordinal suffix | 1st, 2nd, to 31st |
w | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday) |
F | A full textual representation of a month | January through December |
m | Numeric representation of a month, with leading zero | 01 through 12 |
n | Numeric representation of a month, without leading zeros | 1 through 12 |
M | A short textual representation of a month | Jan through Dec |
U | The number of seconds since the Unix Epoch | 1413704993 |
y | A two digit representation of a year | 99 or 03 |
Y | A full numeric representation of a year, 4 digits | 1999 or 2003 |
Character | Description | Example |
---|---|---|
H | Hours (24 hours) | 00 to 23 |
h | Hours | 1 to 12 |
i | Minutes | 00 to 59 |
S | Seconds, 2 digits | 00 to 59 |
s | Seconds | 0, 1 to 59 |
K | AM/PM | AM or PM |
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.