2

我希望使用 jquery 从 datetimepicker ( 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'
    });

});
4

3 回答 3

1

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

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);
于 2015-06-09T12:55:54.997 回答
0

从 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());
});
于 2015-06-09T12:41:26.183 回答
0

您可以使用.date()(ref doc)方法将当前日期作为时刻对象发出

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

由于 datetimepicker 吐出一个 momentjs 对象,因此很容易计算差异(参考文档)

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/

于 2015-06-09T12:50:04.713 回答