Pikaday
A refreshing JavaScript Datepicker — lightweight, no dependencies, modular CSS
Top Related Projects
lightweight, powerful javascript datetimepicker with no dependencies
A powerful Date/time picker widget.
JavaScript Date Range, Date and Time Picker Component
:calendar: Customizable date (and time) picker. Opt-in UI, no jQuery!
Duet Date Picker is an open source version of Duet Design System’s accessible date picker. Try live example at https://duetds.github.io/date-picker/
Quick Overview
Pikaday is a lightweight, modular JavaScript datepicker library with no dependencies. It provides a flexible and customizable solution for adding date selection functionality to web applications, with support for theming and localization.
Pros
- Lightweight and dependency-free, making it easy to integrate into various projects
- Highly customizable with extensive theming options
- Supports both mouse and keyboard navigation for improved accessibility
- Compatible with modern frameworks and libraries like React, Angular, and Vue
Cons
- Limited built-in features compared to some more comprehensive datepicker libraries
- Requires additional configuration for advanced use cases
- Documentation could be more detailed and organized
- Not as actively maintained as some other popular datepicker libraries
Code Examples
- Basic usage:
const picker = new Pikaday({
field: document.getElementById('datepicker'),
format: 'D MMM YYYY',
onSelect: function(date) {
console.log('Selected date:', date);
}
});
- Setting a date range:
const picker = new Pikaday({
field: document.getElementById('datepicker'),
minDate: new Date('2023-01-01'),
maxDate: new Date('2023-12-31')
});
- Customizing the theme:
const picker = new Pikaday({
field: document.getElementById('datepicker'),
theme: 'dark-theme',
yearRange: [2000, 2030],
showWeekNumber: true
});
Getting Started
To use Pikaday in your project, follow these steps:
-
Install Pikaday via npm:
npm install pikaday
-
Import Pikaday in your JavaScript file:
import Pikaday from 'pikaday'; import 'pikaday/css/pikaday.css';
-
Create a new Pikaday instance:
const picker = new Pikaday({ field: document.getElementById('datepicker'), format: 'YYYY-MM-DD' });
-
Add an input field to your HTML:
<input type="text" id="datepicker">
Now you have a basic Pikaday datepicker set up in your project. You can further customize it by exploring the various options available in the Pikaday documentation.
Competitor Comparisons
lightweight, powerful javascript datetimepicker with no dependencies
Pros of flatpickr
- More feature-rich with built-in time picking, range selection, and multiple date selection
- Smaller file size and better performance
- Extensive localization support with 40+ languages available out of the box
Cons of flatpickr
- Steeper learning curve due to more configuration options
- Less customizable styling compared to Pikaday's simpler CSS approach
Code Comparison
Pikaday initialization:
var picker = new Pikaday({
field: document.getElementById('datepicker'),
format: 'D MMM YYYY',
onSelect: function() {
console.log(this.getMoment().format('Do MMMM YYYY'));
}
});
flatpickr initialization:
flatpickr("#datepicker", {
dateFormat: "d M Y",
onChange: function(selectedDates, dateStr, instance) {
console.log(dateStr);
}
});
Both libraries offer simple initialization, but flatpickr's API is more concise and modern. Pikaday relies on Moment.js for date formatting, while flatpickr has built-in date formatting capabilities. flatpickr's configuration options are more extensive, allowing for greater flexibility in a single initialization call.
A powerful Date/time picker widget.
Pros of Tempus Dominus
- More feature-rich, offering date, time, and datetime picker functionality
- Supports multiple frameworks (Bootstrap, jQuery, standalone)
- Active development and regular updates
Cons of Tempus Dominus
- Larger file size and potentially more complex to implement
- Steeper learning curve due to more options and configurations
Code Comparison
Pikaday:
var picker = new Pikaday({
field: document.getElementById('datepicker'),
format: 'D MMM YYYY',
onSelect: function() {
console.log(this.getMoment().format('Do MMMM YYYY'));
}
});
Tempus Dominus:
new tempusDominus.TempusDominus(document.getElementById('datetimepicker'), {
display: {
components: {
clock: true,
date: true
},
format: 'DD MMM YYYY HH:mm'
},
hooks: {
inputFormat: (context, date) => moment(date).format('DD MMM YYYY HH:mm')
}
});
Both libraries offer date picking functionality, but Tempus Dominus provides more built-in options for datetime selection and formatting. Pikaday is simpler and more lightweight, focusing primarily on date selection. The choice between them depends on the specific requirements of your project and the level of complexity you're comfortable with.
JavaScript Date Range, Date and Time Picker Component
Pros of Date Range Picker
- Supports selecting date ranges, not just single dates
- Includes time picker functionality
- Offers pre-defined ranges (e.g., "Last 7 Days", "This Month")
Cons of Date Range Picker
- Larger file size and more complex codebase
- Requires moment.js as a dependency
- Less customizable appearance compared to Pikaday
Code Comparison
Pikaday:
var picker = new Pikaday({
field: document.getElementById('datepicker'),
format: 'D MMM YYYY',
onSelect: function() {
console.log(this.getMoment().format('Do MMMM YYYY'));
}
});
Date Range Picker:
$('input[name="daterange"]').daterangepicker({
opens: 'left',
startDate: moment().startOf('hour'),
endDate: moment().startOf('hour').add(32, 'hour'),
locale: {
format: 'M/DD hh:mm A'
}
});
Both libraries offer date picking functionality, but Date Range Picker provides more advanced features for selecting date ranges and times. However, this comes at the cost of a larger file size and additional dependencies. Pikaday is lighter and more focused on single date selection, making it potentially more suitable for simpler use cases or projects with stricter performance requirements.
:calendar: Customizable date (and time) picker. Opt-in UI, no jQuery!
Pros of Rome
- More feature-rich, offering a complete date/time picker solution
- Supports multiple languages and localization out of the box
- Provides a more modern and customizable UI
Cons of Rome
- Larger file size and potentially higher performance overhead
- Steeper learning curve due to more complex API and configuration options
- Less actively maintained (last update was in 2019)
Code Comparison
Pikaday initialization:
var picker = new Pikaday({
field: document.getElementById('datepicker'),
format: 'D MMM YYYY',
onSelect: function() {
console.log(this.getMoment().format('Do MMMM YYYY'));
}
});
Rome initialization:
rome(document.querySelector('#datepicker'), {
time: false,
inputFormat: 'D MMM YYYY',
dateValidator: rome.val.beforeEq(new Date()),
styles: {
daySelected: 'my-selected-day'
}
});
Both libraries offer simple initialization, but Rome provides more built-in options for customization and validation. Pikaday relies on Moment.js for formatting, while Rome has its own date manipulation utilities. Rome's API is more extensive, allowing for greater flexibility but potentially requiring more setup time.
Duet Date Picker is an open source version of Duet Design System’s accessible date picker. Try live example at https://duetds.github.io/date-picker/
Pros of date-picker
- Built with Web Components, offering better encapsulation and reusability
- Provides a more accessible and customizable interface out-of-the-box
- Supports both mouse and keyboard navigation for improved usability
Cons of date-picker
- Larger file size and potentially higher performance overhead
- Less widespread adoption and community support compared to Pikaday
- May require additional setup for integration with some frameworks
Code Comparison
date-picker:
<duet-date-picker identifier="date" name="date"></duet-date-picker>
Pikaday:
var picker = new Pikaday({
field: document.getElementById('datepicker'),
format: 'D MMM YYYY',
onSelect: function() {
console.log(this.getMoment().format('Do MMMM YYYY'));
}
});
The date-picker example shows a more concise implementation using Web Components, while Pikaday requires JavaScript initialization and configuration. date-picker's approach may be easier to integrate for some developers, but Pikaday offers more fine-grained control over the picker's behavior and appearance.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Pikaday
A refreshing JavaScript Datepicker
- Lightweight (less than 5kb minified and gzipped)
- No dependencies (but plays well with Moment.js)
- Modular CSS classes for easy styling
Production ready? Since version 1.0.0 Pikaday is stable and used in production. If you do however find bugs or have feature requests please submit them to the GitHub issue tracker. Also see the changelog
Installation
You can install Pikaday as an NPM package:
npm install pikaday
Or link directly to the CDN:
<script src="https://cdn.jsdelivr.net/npm/pikaday/pikaday.js"></script>
Styles
You will also need to include Pikaday CSS file. This step depends on how Pikaday was installed. Either import from NPM:
@import './node_modules/pikaday/css/pikaday.css';
Or link to the CDN:
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css">
Usage
Pikaday can be bound to an input field:
<input type="text" id="datepicker">
Add the JavaScript to the end of your document:
<script src="pikaday.js"></script>
<script>
var picker = new Pikaday({ field: document.getElementById('datepicker') });
</script>
If you're using jQuery make sure to pass only the first element:
var picker = new Pikaday({ field: $('#datepicker')[0] });
If the Pikaday instance is not bound to a field you can append the element anywhere:
var field = document.getElementById('datepicker');
var picker = new Pikaday({
onSelect: function(date) {
field.value = picker.toString();
}
});
field.parentNode.insertBefore(picker.el, field.nextSibling);
Formatting
By default, dates are formatted and parsed using standard JavaScript Date object.
If Moment.js is available in scope, it will be used to format and parse input values. You can pass an additional format
option to the configuration which will be passed to the moment
constructor.
See the moment.js example for a full version.
<input type="text" id="datepicker" value="9 Oct 2014">
<script src="moment.js"></script>
<script src="pikaday.js"></script>
<script>
var picker = new Pikaday({
field: document.getElementById('datepicker'),
format: 'D MMM YYYY',
onSelect: function() {
console.log(this.getMoment().format('Do MMMM YYYY'));
}
});
</script>
For more advanced and flexible formatting you can pass your own toString
function to the configuration which will be used to format the date object.
This function has the following signature:
toString(date, format = 'YYYY-MM-DD')
You should return a string from it.
Be careful, though. If the formatted string that you return cannot be correctly parsed by the Date.parse
method (or by moment
if it is available), then you must provide your own parse
function in the config. This function will be passed the formatted string and the format:
parse(dateString, format = 'YYYY-MM-DD')
var picker = new Pikaday({
field: document.getElementById('datepicker'),
format: 'D/M/YYYY',
toString(date, format) {
// you should do formatting based on the passed format,
// but we will just return 'D/M/YYYY' for simplicity
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${day}/${month}/${year}`;
},
parse(dateString, format) {
// dateString is the result of `toString` method
const parts = dateString.split('/');
const day = parseInt(parts[0], 10);
const month = parseInt(parts[1], 10) - 1;
const year = parseInt(parts[2], 10);
return new Date(year, month, day);
}
});
Configuration
As the examples demonstrate above Pikaday has many useful options:
field
bind the datepicker to a form fieldtrigger
use a different element to trigger opening the datepicker, see trigger example (default tofield
)bound
automatically show/hide the datepicker onfield
focus (defaulttrue
iffield
is set)ariaLabel
data-attribute on the input field with an aria assistance text (only applied whenbound
is set)position
preferred position of the datepicker relative to the form field, e.g.:top right
,bottom right
Note: automatic adjustment may occur to avoid datepicker from being displayed outside the viewport, see positions example (default to 'bottom left')reposition
can be set to false to not reposition datepicker within the viewport, forcing it to take the configuredposition
(default: true)container
DOM node to render calendar into, see container example (default: undefined)format
the default output format for.toString()
andfield
value (requires Moment.js for custom formatting)formatStrict
the default flag for moment's strict date parsing (requires Moment.js for custom formatting)toString(date, format)
function which will be used for custom formatting. This function will take precedence overmoment
.parse(dateString, format)
function which will be used for parsing input string and getting a date object from it. This function will take precedence overmoment
.defaultDate
the initial date to view when first openedsetDefaultDate
Boolean (true/false). make thedefaultDate
the initial selected valuefirstDay
first day of the week (0: Sunday, 1: Monday, etc)minDate
the minimum/earliest date that can be selected (this should be a native Date object - e.g.new Date()
ormoment().toDate()
)maxDate
the maximum/latest date that can be selected (this should be a native Date object - e.g.new Date()
ormoment().toDate()
)disableWeekends
disallow selection of Saturdays or SundaysdisableDayFn
callback function that gets passed a Date object for each day in view. Should return true to disable selection of that day.yearRange
number of years either side (e.g.10
) or array of upper/lower range (e.g.[1900,2015]
)showWeekNumber
show the ISO week number at the head of the row (defaultfalse
)pickWholeWeek
select a whole week instead of a day (defaultfalse
)isRTL
reverse the calendar for right-to-left languagesi18n
language defaults for month and weekday names (see internationalization below)yearSuffix
additional text to append to the year in the titleshowMonthAfterYear
render the month after year in the title (defaultfalse
)showDaysInNextAndPreviousMonths
render days of the calendar grid that fall in the next or previous months (default: false)enableSelectionDaysInNextAndPreviousMonths
allows user to select date that is in the next or previous months (default: false)numberOfMonths
number of visible calendarsmainCalendar
whennumberOfMonths
is used, this will help you to choose where the main calendar will be (defaultleft
, can be set toright
). Only used for the first display or when a selected date is not already visibleevents
array of dates that you would like to differentiate from regular days (e.g.['Sat Jun 28 2017', 'Sun Jun 29 2017', 'Tue Jul 01 2017',]
)theme
define a classname that can be used as a hook for styling different themes, see theme example (defaultnull
)blurFieldOnSelect
defines if the field is blurred when a date is selected (defaulttrue
)onSelect
callback function for when a date is selectedonOpen
callback function for when the picker becomes visibleonClose
callback function for when the picker is hiddenonDraw
callback function for when the picker draws a new monthkeyboardInput
enable keyboard input support (defaulttrue
)
Styling
If the reposition
configuration-option is enabled (default), Pikaday will apply CSS-classes to the datepicker according to how it is positioned:
top-aligned
left-aligned
right-aligned
bottom-aligned
Note that the DOM element at any time will typically have 2 CSS-classes (eg. top-aligned right-aligned
etc).
jQuery Plugin
The normal version of Pikaday does not require jQuery, however there is a jQuery plugin if that floats your boat (see plugins/pikaday.jquery.js
in the repository). This version requires jQuery, naturally, and can be used like other plugins:
See the jQuery example for a full version.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="pikaday.js"></script>
<script src="plugins/pikaday.jquery.js"></script>
<script>
// activate datepickers for all elements with a class of `datepicker`
$('.datepicker').pikaday({ firstDay: 1 });
// chain a few methods for the first datepicker, jQuery style!
$('.datepicker').eq(0).pikaday('show').pikaday('gotoYear', 2042);
</script>
AMD support
If you use a modular script loader, Pikaday is not bound to the global object and will fit nicely in your build process. You can require Pikaday just like any other module. See the AMD example for a full version.
require(['pikaday'], function(Pikaday) {
var picker = new Pikaday({ field: document.getElementById('datepicker') });
});
The same applies for the jQuery plugin mentioned above. See the jQuery AMD example for a full version.
require(['jquery', 'pikaday.jquery'], function($) {
$('#datepicker').pikaday();
});
CommonJS module support
If you use a CommonJS compatible environment you can use the require function to import Pikaday.
var pikaday = require('pikaday');
When you bundle all your required modules with Browserify and you don't use Moment.js specify the ignore option:
browserify main.js -o bundle.js -i moment
Ruby on Rails
If you're using Ruby on Rails, make sure to check out the Pikaday gem.
Methods
You can control the date picker after creation:
var picker = new Pikaday({ field: document.getElementById('datepicker') });
Get and set date
picker.toString('YYYY-MM-DD')
Returns the selected date in a string format. If Moment.js exists (recommended) then Pikaday can return any format that Moment understands.
You can also provide your own toString
function and do the formatting yourself. Read more in the formatting section.
If neither moment
object exists nor toString
function is provided, JavaScript's default .toDateString()
method will be used.
picker.getDate()
Returns a basic JavaScript Date
object of the selected day, or null
if no selection.
picker.setDate('2015-01-01')
Set the current selection. This will be restricted within the bounds of minDate
and maxDate
options if they're specified. You can optionally pass a boolean as the second parameter to prevent triggering of the onSelect callback (true), allowing the date to be set silently.
picker.getMoment()
Returns a Moment.js object for the selected date (Moment must be loaded before Pikaday).
picker.setMoment(moment('14th February 2014', 'DDo MMMM YYYY'))
Set the current selection with a Moment.js object (see setDate
for details).
Clear and reset date
picker.clear()
Will clear and reset the input where picker is bound to.
Change current view
picker.gotoDate(new Date(2014, 1))
Change the current view to see a specific date. This example will jump to February 2014 (month is a zero-based index).
picker.gotoToday()
Shortcut for picker.gotoDate(new Date())
picker.gotoMonth(2)
Change the current view by month (0: January, 1: Februrary, etc).
picker.nextMonth()
picker.prevMonth()
Go to the next or previous month (this will change year if necessary).
picker.gotoYear()
Change the year being viewed.
picker.setMinDate()
Update the minimum/earliest date that can be selected.
picker.setMaxDate()
Update the maximum/latest date that can be selected.
picker.setStartRange()
Update the range start date. For using two Pikaday instances to select a date range.
picker.setEndRange()
Update the range end date. For using two Pikaday instances to select a date range.
Show and hide datepicker
picker.isVisible()
Returns true
or false
.
picker.show()
Make the picker visible.
picker.adjustPosition()
Recalculate and change the position of the picker.
picker.hide()
Hide the picker making it invisible.
picker.destroy()
Hide the picker and remove all event listeners â no going back!
Internationalization
The default i18n
configuration format looks like this:
i18n: {
previousMonth : 'Previous Month',
nextMonth : 'Next Month',
months : ['January','February','March','April','May','June','July','August','September','October','November','December'],
weekdays : ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
weekdaysShort : ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
}
You must provide 12 months and 7 weekdays (with abbreviations). Always specify weekdays in this order with Sunday first. You can change the firstDay
option to reorder if necessary (0: Sunday, 1: Monday, etc). You can also set isRTL
to true
for languages that are read right-to-left.
Extensions
Timepicker
Pikaday is a pure datepicker. It will not support picking a time of day. However, there have been efforts to add time support to Pikaday. See #1 and #18. These reside in their own fork.
You can use the work @owenmead did most recently at owenmead/Pikaday A more simple time selection approach done by @xeeali at xeeali/Pikaday is based on version 1.2.0. Also @stas has a fork stas/Pikaday, but is now quite old
Browser Compatibility
- IE 7+
- Chrome 8+
- Firefox 3.5+
- Safari 3+
- Opera 10.6+
Authors
- David Bushell https://dbushell.com @dbushell
- Ramiro Rikkert GitHub @RamRik
Thanks to @shoogledesigns for the name.
Copyright © 2014 David Bushell | BSD & MIT license
Top Related Projects
lightweight, powerful javascript datetimepicker with no dependencies
A powerful Date/time picker widget.
JavaScript Date Range, Date and Time Picker Component
:calendar: Customizable date (and time) picker. Opt-in UI, no jQuery!
Duet Date Picker is an open source version of Duet Design System’s accessible date picker. Try live example at https://duetds.github.io/date-picker/
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot