Bootstrap 3 Datepicker v4 - set default date

18,727

Solution 1

Are you sure your date variable is a Date object? If it is not, you will need to set the default date like this:

var date = json[0]['date'];
$(function () {
    $('#datetimepicker-edit-cost').datetimepicker({
        locale: 'cs',
        format:'DD.MM.YYYY',
        defaultDate: new Date(date)
    });
});

More information about the date property for that plugin:

http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#date

date([newDate])

Takes newDate string, Date, moment, null parameter and sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.

Throws

TypeError - in case the newDate cannot be parsed

Emits

change.dp - In case newDate is different from current moment

Solution 2

As also mentioned in the answer by John Washam, the documentation clearly says that the date function accepts a moment object, among others.
I was in the same situation, trying various things, but nothing seemed to work, except for this idea:
Why not feed a moment object to the date function?

var date = json[0]['date'];
$(function () {
   $('#datetimepicker-edit-cost').datetimepicker({
      locale: 'cs',
      format:'DD.MM.YYYY'
   });
   $('#datetimepicker-edit-cost').data("DateTimePicker").date(moment(date));
});

Since the moment.js library is required for the datepicker to work, you can use it to parse any string, and directly feed the date function with its result.

Share:
18,727
porosman
Author by

porosman

Updated on June 18, 2022

Comments

  • porosman
    porosman almost 2 years

    im using this datetimepicker http://eonasdan.github.io/bootstrap-datetimepicker/ in my edit form. Im not able to set up default value in this datetimepicker from my variable date. If I use $('#edit_cost_date').val(json[0]['date']); on input element, the value in input is right but if i open datetimepicker i see that marked is not the date in input but actual date.

    var date = json[0]['date'];
    $(function () {
        $('#datetimepicker-edit-cost').datetimepicker({
            locale: 'cs',
            format:'DD.MM.YYYY'
        });
    });
    
  • porosman
    porosman about 9 years
    actualy, i have tried it but with no success...always set me todays date. I have tried it with diferent formats strings and moments
  • keune
    keune over 7 years
    bootstrap 3 datepicker turned out to be the least developer-friendly widget i have ever used.