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

3

9

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.

Constitutionalism answered 25/11, 2017 at 20:19 Comment(5)
I think you can acces on html input so i dont know that would you like to use as moment element then you can use i o change event then can reach via params e.date as moment cloned elementRoentgenotherapy
I would think there is a simple way date object which should be a moment object which is what I am looking for.Constitutionalism
$('#datetimepicker').datetimepicker('date') works for me, can you provide a snippet or a fiddle showing the issue?Scibert
@Constitutionalism did yo managed to solve the problem you were facing.Binford
this is the worst plugin everCallum
H
18

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/

Hymenium answered 25/11, 2017 at 20:36 Comment(5)
This will catch the date on the change event. This is different than what I need. I need to simple set a variable to the data outside an event.Constitutionalism
You said : "However, I need to be able to get the selected date from it.". There is no binding, you only can get date from an event. It's jQuery, not Angular...Hymenium
Updated answer, but anyway, you need to call it using event functions.Hymenium
In my case, change event it is triggered twice every time I change the date. I use hide.datetimepicker insteadReedy
The downside of this , is that the above yields current date/time , if no value is set.Lookeron
F
6

In case anybody was experiencing the same trouble as me (using bootstrap v4 https://tempusdominus.github.io/bootstrap-4/), and wanting the date at the time the picker is closed, here is the code:

$(function () {
    $('#datetimepicker').datetimepicker();
    $('#datetimepicker').on("datetimepicker.hide", function (e) {
        console.log(moment(e.date).format('YYYY-MM-DD HH:mm'));
    });
});

Note that in this case, datetimepicker comes before hide, which is different to change coming before datetimepicker. Using hide.datetimepicker will not work.

Forfeiture answered 17/4, 2018 at 10:32 Comment(0)
B
1

Maybe i am wrong but the way I interpret "Note All options are accessed via the data attribute" it says to access the functions in the following format

$("#YOU_SELECTOR").data('DateTimePicker').FUNCTION();

if you try to console.log($("#YOU_SELECTOR").data('DateTimePicker'));

You will see that it prints all those functions that it says are accessible via data attribute, a few I am printing below

{
    "destroy": function () {
        H(), I(), i.widget.remove(), i.element.removeData("DateTimePicker"), i.component && i.component.removeData("DateTimePicker")
    },
    "show": function (a) {
        if (!l().prop("disabled")) {
            if (i.options.useCurrent && "" === l().val()) {
                if (1 !== i.options.minuteStepping) {
                    var c = b(),
                        d = i.options.minuteStepping;
                    c.minutes(Math.round(c.minutes() / d) * d % 60).seconds(0), i.setValue(c.format(i.format))
                } else i.setValue(b().format(i.format));
                o("", a.type)
            }
            a && "click" === a.type && i.isInput && i.widget.hasClass("picker-open") || (i.widget.hasClass("picker-open") ? (i.widget.hide(), i.widget.removeClass("picker-open")) : (i.widget.show(), i.widget.addClass("picker-open")), i.height = i.component ? i.component.outerHeight() : i.element.outerHeight(), n(), i.element.trigger({
                type: "dp.show",
                date: b(i.date)
            }), G(), a && B(a))
        }
    },
    "disable": function () {
        var a = l();
        a.prop("disabled") || (a.prop("disabled", !0), H())
    },
    "enable": function () {
        var a = l();
        a.prop("disabled") && (a.prop("disabled", !1), F())
    },
    "hide": function () {
        var a, c, d = i.widget.find(".collapse");
        for (a = 0; a < d.length; a++)
            if (c = d.eq(a).data("collapse"), c && c.transitioning) return;
        i.widget.hide(), i.widget.removeClass("picker-open"), i.viewMode = i.startViewMode, E(), i.element.trigger({
            type: "dp.hide",
            date: b(i.date)
        }), I()
    },
    "setValue": function (a) {
        b.locale(i.options.language), a ? i.unset = !1 : (i.unset = !0, K()), a = b.isMoment(a) ? a.locale(i.options.language) : a instanceof Date ? b(a) : b(a, i.format, i.options.useStrict), a.isValid() ? (i.date = a, K(), i.viewDate = b({
            y: i.date.year(),
            M: i.date.month()
        }), t(), x()) : p(a)
    },
    "getDate": function () {
        return i.unset ? null : b(i.date)
    },
    "setDate": function (a) {
        var c = b(i.date);
        i.setValue(a ? a : null), o(c, "function")
    },
    "setDisabledDates": function (a) {
        i.options.disabledDates = O(a), i.viewDate && q()
    },
    "setEnabledDates": function (a) {
        i.options.enabledDates = O(a), i.viewDate && q()
    },
    "setMaxDate": function (a) {
        void 0 !== a && (i.options.maxDate = b.isMoment(a) || a instanceof Date ? b(a) : b(a, i.format, i.options.useStrict), i.viewDate && q())
    },
    "setMinDate": function (a) {
        void 0 !== a && (i.options.minDate = b.isMoment(a) || a instanceof Date ? b(a) : b(a, i.format, i.options.useStrict), i.viewDate && q())
    }
    .............. and more,

see below calling getDate() in the demo via a click of a link. you can check after changing the date to verify.

$(document).ready(function() {
  var picker = $('#datetimepicker7').datetimepicker();

  //console.log(picker.datetimepicker('data-view-date'));
  //console.log($('#datetimepicker7').datetimepicker('data-show'));

  $("#tog").on('click', function() {
    //console.log($('#datetimepicker7').data('DateTimePicker'));
    console.log($('#datetimepicker7').data('DateTimePicker').getDate());
  })

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.4/js/bootstrap-datetimepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.4/css/bootstrap-datetimepicker.css" rel="stylesheet" />




<div class="container">
  <div class='col-md-5'>
    <div class="form-group">
      <div class="input-group date" id="datetimepicker7" data-target-input="nearest">
        <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker7" />
        <span class="input-group-addon" data-target="#datetimepicker7" data-toggle="datetimepicker">
                    <span class="glyphicon glyphicon-calendar"></span>
        </span>
      </div>
    </div>
  </div>
  <a href="#." id="tog">toggle</a>
</div>
Binford answered 25/11, 2017 at 22:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.