Search code examples
jquerytwitter-bootstrap-3bootstrap-datetimepicker

Datetimepicker: default value only set every other time


After solving the previous defaultDate issue, I have a new one. The JavaScript code is as follows:

$(function () {
    $('#datepicker').datetimepicker({
        useCurrent: false,
        maxDate: moment().toDate(),
        locale: 'de',
        defaultDate: moment().toDate(),
        format: 'DD.MM.YYYY'
    });
});

When I visit the page, the default date is not set. When I reload it, the default date is set, and stays set whatever I do, until I browse to another page and then return to the form; then, the default date is usually not set, although sometimes it is. When it is not set, the date picker does not work (a click on the input field has no effect), and the console shows an error message:

Uncaught TypeError: defaultDate() date passed is invalid according to component setup validations

On JSFiddle, the behaviour is even stranger. On first load, the date is usually not set. On further reloads, it is set, except that sometimes, if you click Run often enough, it isn't. It looks like a bug to me, but since I do not really know JavaScript, I thought I'd ask...


Solution

  • The issue is caused by the restriction on maxDate and defaultDate being the exact same date. The reason this error is sporadic is because occasionally there is a delay of a few milliseconds between the dates as processing occurs. When this delay is not present, you get the error.

    To fix it you can manually add one second to the maxDate to cover any processing time discrepancies. Try this:

    $(function () {
        var maxDate = moment().add(1, 'seconds').toDate();
        var defaultDate = moment().toDate();
    
        $('#datepicker').datetimepicker({
            useCurrent: false,
            maxDate: maxDate,
            locale: 'de',
            defaultDate: defaultDate,
            format: 'DD.MM.YYYY'
        });
    });
    

    Updated fiddle