Asa Carter Asa Carter - 3 months ago 9
Javascript Question

Bootstrap Datetime picker always sets date to Jauary 20 2016

I'm trying to initialize a Bootstrap datetime picker from the form field value.

http://eonasdan.github.io/bootstrap-datetimepicker/

The date picker always displays "January 20, 2016" when it initializes even though the moment object is correct.

I can't see what I'm doing wrong. I've also tried just using a string.

HTML

<label for="timer-date">End date</label>
<input type="text" id="timer-date" class="form-control" value="2016-12-15">
<label for="timer-time">End time</label>
<input type="text" id="timer-time" class="form-control" value="20:54:00">


JS

$(function() {

var date = $('#timer-date').val() + ' ' + $('#timer-time').val();
console.log (date);
// 2016-12-15 20:54:00

var date_obj = moment(date);
console.log (date_obj);
// _d Date {Thu Dec 15 2016 20:54:00 GMT+0000 (GMT Daylight Time)}


$('#timer-date').datetimepicker({
format: 'LL',
defaultDate: date_obj
});

$('#timer-time').datetimepicker({
format: 'LT',
defaultDate: date_obj
});
});

Answer

EDIT : ("bootstrap datetime picker" does support momentjs dates).

The issue are the value attributes, you need to clear them once you read them or put your data in data attributes for instance.

Working jsfiddle

var date = $('#timer-date').val() + ' ' + $('#timer-time').val();
  console.log (date);   // 2016-12-15 20:54:00
  $('#timer-date').val("");
  $('#timer-time').val("");

  var date_obj = moment(date);
  console.log (date_obj); 
  // _d    Date {Thu Dec 15 2016 20:54:00 GMT+0000 (GMT Daylight Time)}

   $('#timer-date-wrapper').datetimepicker({
      format: 'LL',
      defaultDate: date_obj
  });

  $('#timer-time-wrapper').datetimepicker({
    format: 'LT',
    defaultDate: date_obj
  });