Date Pickers in Bootstrap Studio

Date Pickers are controls that let users select dates and time periods. Browsers have basic date selection built-in, but for advanced use cases you often need a custom solution.

Luckily, this is easy to do in Bootstrap Studio. In this lesson, we will include the elegant Lightpick library, which supports both date and period selection.

You can download the complete example as a bsdesign file. Download Example

Importing the Library from a CDN

To start, import the following two JavaScript libraries using the Link External functionality in Bootstrap Studio's Design panel. The first is moment.js and the second is lightpick itself:

  • https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js
  • https://cdn.jsdelivr.net/npm/lightpick@1.3.4/lightpick.min.js

Because Lightpick depends on moment.js for date calculations, make sure moment is included first in the page by specifying the JavaScript include order.

After this, you need to include Lightpick's CSS by linking this file with Link External in the CSS group:

https://cdn.jsdelivr.net/npm/lightpick@1.3.4/css/lightpick.min.css

Initializing the Date Pickers

At this point, the date picker is added to your page, but it isn't displayed. For this, we will need a bit of JavaScript. Add the following code to a file named datepicker.js:

$(function(){
    
    let datePicker = document.getElementById('datePicker');
    let picker = new Lightpick({
        field: datePicker,
        onSelect: function(date){
            datePicker.value = date.format('Do MMMM YYYY');
        }
    });
    
    let dateRangePicker = document.getElementById('dateRangePicker');
    let pickerRange = new Lightpick({
        field: dateRangePicker,
        singleDate: false,
        onSelect: function(start, end){
            let str = '';
            str += start ? start.format('Do MMMM YYYY') + ' to ' : '';
            str += end ? end.format('Do MMMM YYYY') : '...';
            dateRangePicker.value = str;
        }
    });
});

This will display a regular date picker when the first field is selected, and a date range picker for the second. When a date is selected, we will just add it to the field as a value.

Notice that the parameters that are passed to the onSelect function are moment.js object. This makes it very easy to use one the library's powerful format method to turn the date into a human readable form. And with this our date pickers are ready!