从 datetimepicker 获取值 bootstrap 3

Get value from datetimepicker bootstrap 3

我希望使用 jquery 从日期时间选择器 (http://eonasdan.github.io/bootstrap-datetimepicker/) 中获取日期值,以找出 2 个输入日期之间的差异。我花了几天时间去做,但一点运气都没有。这是我的代码:

HTML

<div class="col-sm-4">
    <label for="label_duration" id="lblStartDate" 
           class="col-sm-2 control-label">Start Date</label>
    <div class='input-group date' id='datetimepicker1'>
        <input type='text' class="form-control" name="startdate" 
               id="startdate" placeholder="yyyy-mm-dd"  required/>
        <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
</div>

<div class="col-sm-4">
    <label for="label_duration" id="lblEndDate"  class="col-sm-2 
           control-label">End Date</label>
    <div class='input-group date' id='datetimepicker2'>
        <input type='text' class="form-control" name="enddate" id="enddate" 
               placeholder="yyyy-mm-dd" required/>
        <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
</div>

jQuery

$(function () {
    $('#datetimepicker1').datetimepicker({
        viewMode: 'years',
        format: 'YYYY-MM-DD'
    });

    $('#datetimepicker2').datetimepicker({
        viewMode: 'years',
        format: 'YYYY-MM-DD'
    });

});

来自 API 文档 (http://tarruda.github.io/bootstrap-datetimepicker/):

// Considering you are on a GMT-3 timezone and the input contains '2000-01-17 10:00'
var localDate = picker.getLocalDate(); // localDate === 2000-01-17 07:00
var utcDate = picker.getDate(); // utcDate === 2000-01-17 10:00

或处理 changeDate 事件:

el.on('changeDate', function(e) {
  console.log(e.date.toString());
  console.log(e.localDate.toString());
});

你可以使用.date()(ref doc) method which emits the current date as a moment对象

var mydatetimepicker = $('#datetimepicker1').datetimepicker();
var dtp = mydatetimepicker.data('DateTimePicker');
console.log(dtp.date());

由于 datetimepicker 吐出一个 momentjs 对象,因此很容易计算出差异 (ref docs)

var mydatetimepicker1 = $('#datetimepicker1').datetimepicker();
var dtp1 = mydatetimepicker1.data('DateTimePicker');

var mydatetimepicker2 = $('#datetimepicker2').datetimepicker();
var dtp2 = mydatetimepicker2.data('DateTimePicker');

var start = dtp1.date();
var end = dtp2.date();

var diff = end.diff(start);
console.log(diff);

这是一个演示 http://jsfiddle.net/dhirajbodicherla/0Ltv25o8/1241/

两个字符串之间的天数差异:

var diffInDays = (new Date('1970-01-01').valueOf()-new Date('1970-01-02').valueOf())/(3600*24*1000);

您的两个输入之间的天数差异:

var diffInDays = (new Date($('#startdate').val()).valueOf()-new Date($('#enddate').val()).valueOf())/(3600*24*1000);