Explain Codes LogoExplain Codes Logo

Disable time in bootstrap date time picker

javascript
datetimepicker
momentjs
internationalization
Alex KataevbyAlex Kataev·Sep 29, 2024
TLDR

Gracefully transition to date-only mode in the Bootstrap datetime picker by simply adjusting its format property to 'YYYY-MM-DD' in the initialization process:

$('.datetimepicker').datetimepicker({ format: 'YYYY-MM-DD' // Putting license plates aside, this format just does the trick for disabling time });

This action effectively makes the time components vanish, paving the way for pure date selection.

In-depth study: Mastering date-only display

The charm of disabling the time component lies in transforming the picker's initialization, supplying the 'YYYY-MM-DD' format which morphs your picker into a date exclusive selector.

When catering to users across different geographic areas, Moment.js comes to the rescue, offering locale-based formats. Achieve this by swapping the format to 'L', which adapts the date format as per the browser locale:

$('.datetimepicker').datetimepicker({ format: 'L' // No worries about mixing up dates and months anymore });

Version-specific adjustments

The process for disabling time may vary a bit depending on the Bootstrap version:

  • For version 3, utilizing pickTime: false disables time selection:
$('#datetimepicker4').datetimepicker({ pickTime: false // Time? We don't do that here });
  • Version 4, on the other hand, handles this automatically for you. Just ignoring time in the format string would suffice.

Leverage momento.js for internationalization

When you wish to make your date picker friendly for a global audience, Moment.js's versatile localized date and time formats are a perfect ally. Feel free to review the Moment.js docs for additional localisation options.

Harmonize design to match your site theme

Ensuring your datetime picker seamlessly aligns with your site’s design is pivotal for a cohesive look and feel. Bootstrap's .container and .row classes ensure your datetime picker is always in style.

Consistent frontend experience

While modifying picker functionality, it's important to:

  • Monitor glyphicons to reflect changes. The absence of the glyphicon-time icon subtly hints users that the date-only mode is active.
  • Inspect if the picker’s layout adheres to the 'form-control' class to maintain interface consistency.

Verifying and testing

Comprehensive testing of your implementation ensures its reliability. Check if the time component is truly out of sight and verify that dates are accurately reflected:

$('#datetimepicker4').on("dp.change", function(e) { console.log(e.date); // A peek into the future... or past, depends on the date you've picked });

This will confirm that your picker is functioning as planned and ready for deployment.