How can I get date object from a bootstrap-datetime-picker plugin?

Jaylen picture Jaylen · Nov 25, 2017 · Viewed 10.5k times · Source

I am trying to utilize tempusdominus-datetimepicker-3 to create a date-time picker in my html-forms.

However, I need to be able to get the selected date from it. The plugin has an option called date which according to the document should return a moment object or null. Here is what the document say about this option

Returns the component's model current date, a moment object or null if not set

However, I am struggling to access the date option.

Also from the doc

Note All options are accessed via the data attribute e.g. $('#datetimepicker').datetimepicker(OPTION, ARGUMENT)

So I tried the following to access the date option.

from = $('#datetimepicker').datetimepicker('date');
from = $('#datetimepicker').datetimepicker('data', 'date');
from = $('#datetimepicker').datetimepicker('data').date;
from = $('#datetimepicker').datetimepicker(function(e){
    return e.date;
});

But none of the above is returning the object. How can I access the date object?

I would think a nice plugin like this one will have more readable option like getDate(), setDate(date), getFomat() and setFormat(...) etc; or event examples, which should eliminate questions like this one, but unfortunately it does not.

Answer

Vincent Decaux picture Vincent Decaux · Nov 25, 2017

Here is the correct code to access events :

$(function() {
   $('#datetimepicker').datetimepicker();
   $('#datetimepicker').on("change.datetimepicker", function (e) {
      console.log(e.date);
   });
 });

You can get date using this too :

var date = $('#datetimepicker').datetimepicker('viewDate')

Complete fiddle to manipulate the date : https://jsfiddle.net/10xzksm0/2/