如何从bootstrap-datetime-picker插件中获取日期对象?

9
我正在尝试使用tempusdominus-datetimepicker-3在我的html表单中创建日期时间选择器。然而,我需要能够从中获取所选日期。该插件有一个名为date的选项,根据文档,它应返回一个moment对象或null。以下是文档对此选项的说明:
返回组件的模型当前日期,即moment对象,如果未设置则返回null。
然而,我无法访问date选项。
此外,从文档中可以看到:
注意:所有选项都通过data属性访问,例如$('#datetimepicker').datetimepicker(OPTION, ARGUMENT)。
因此,我尝试了以下方法来访问date选项。
from = $('#datetimepicker').datetimepicker('date');
from = $('#datetimepicker').datetimepicker('data', 'date');
from = $('#datetimepicker').datetimepicker('data').date;
from = $('#datetimepicker').datetimepicker(function(e){
    return e.date;
});

但是上面的内容都没有返回对象。我该如何访问日期对象?
我认为像这样的好插件应该有更易读的选项,比如getDate()setDate(date)getFormat()setFormat(...)等;或者甚至提供一些示例,这样就可以消除类似这样的问题,但不幸的是它没有。

我认为你可以访问HTML输入,所以我不知道你想要将其用作时刻元素,然后你可以使用IO更改事件,然后可以通过参数e.date作为克隆元素来访问。 - Ferhat BAŞ
我认为有一个简单的方法可以将日期对象转换成moment对象,这正是我所需要的。 - Jaylen
$('#datetimepicker').datetimepicker('date') 对我有效,您能否提供一个代码片段或演示页面来展示问题? - VincenzoC
@Jaylen,你解决了你遇到的问题吗? - Muhammad Omer Aslam
1
这是有史以来最糟糕的插件。 - Leandro Bardelli
3个回答

15

这是正确的代码以访问事件:

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

你也可以使用这个来获取日期:

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

完整的 JSFiddle 示例代码,用于操作日期:https://jsfiddle.net/10xzksm0/2/


这将捕获更改事件上的日期。这与我所需的不同。我需要在事件外部将变量简单设置为数据。 - Jaylen
你说:“然而,我需要能够从中获取所选日期。”没有绑定,你只能从事件中获取日期。这是jQuery,不是Angular... - Vincent Decaux
已更新答案,但无论如何,您需要使用事件函数调用它。 - Vincent Decaux
在我的情况下,每次更改日期时,更改事件会触发两次。我使用hide.datetimepicker来代替。 - Simion
1
这样做的缺点是,如果没有设置值,上述代码会返回当前日期/时间。 - Rpant

6

如果有人像我一样遇到了麻烦(使用Bootstrap v4 https://tempusdominus.github.io/bootstrap-4/),并且想要在选择器关闭时获取日期,这里是代码:

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

请注意,在这种情况下,datetimepicker出现在hide之前,与change先于datetimepicker的情况不同。使用hide.datetimepicker将无效。

1
也许我理解有误,但我对“请注意,所有选项都通过数据属性访问”的解释是要以以下格式访问函数。

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

如果你尝试 console.log($("#YOU_SELECTOR").data('DateTimePicker'));,你会看到它打印出所有在data属性中标明可以访问的函数,以下是我打印出来的一些。
{
    "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,

在示例中通过点击链接调用getDate(),请参见下文。更改日期后,您可以进行验证。

$(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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接