从datetimepicker bootstrap获取价值3

时间:2015-06-09 12:28:55

标签: jquery twitter-bootstrap bootstrap-datetimepicker

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

});

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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

OR处理changeDate事件:

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

答案 2 :(得分:0)

您可以使用.date() (ref doc)方法将当前日期作为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/