我在jsfiddle中有以下代码段。我正在尝试将给定的数字添加到日历中。
HTML代码:
<input id="firstDate"/>
<input type="hidden" value="11" id="days">
<br/>
<input id="secondDate"/>
使用Javascript:
<script>
var pickerOptsGeneral = {
format: "dd/mm/yyyy",
autoclose: true,
minView: 2,
maxView: 2
};
$('#firstDate')
.datetimepicker(pickerOptsGeneral)
.on('changeDate', function(ev){
var days = document.getElementById("days").value;
var oldDate = new Date(ev.date);
var newDate = new Date();
newDate.setDate(oldDate.getDate() + days);
secondDate.val(newDate.getDate()+"/"+(newDate.getMonth()+1)+"/"+newDate.getFullYear());
secondDate.datetimepicker('update');
});
var secondDate = $('#secondDate').datetimepicker(pickerOptsGeneral);
</script>
以上代码添加了几个月而不是几天。如果我选择日期
01/06/2017
输出为19/9/2017
如果我对日期进行硬编码:
newDate.setDate(oldDate.getDate() + 11);
这会给我想要的输出。任何人都可以帮我吗?
答案 0 :(得分:1)
试试这个......
var pickerOptsGeneral = {
format: "dd/mm/yyyy",
autoclose: true,
minView: 2,
maxView: 2
};
$('#firstDate')
.datetimepicker(pickerOptsGeneral)
.on('changeDate', function(ev){
var days = parseInt(document.getElementById("days").value);
var oldDate = $("#firstDate").data("datetimepicker").getDate();
var oldDateOriginal = new Date(oldDate);
var newDate = new Date(oldDateOriginal);
newDate.setDate(newDate.getDate() + days);
secondDate.val(newDate.getDate()+"/"+(newDate.getMonth()+1)+"/"+newDate.getFullYear());
secondDate.datetimepicker('update');
});
var secondDate = $('#secondDate').datetimepicker(pickerOptsGeneral);
JSFfiddle链接相同 - http://jsfiddle.net/sdyoxx2r/9/
答案 1 :(得分:0)
当你得到<input type="hidden" value="11" id="days" />
的值时,它会将值作为字符串返回。
因此您需要将天数值从字符串转换为整数。
var pickerOptsGeneral = {
format: "dd/mm/yyyy",
autoclose: true,
minView: 2,
maxView: 2
};
$('#firstDate').datetimepicker(pickerOptsGeneral).on('changeDate',function(ev){
var days = parseInt($('#days').val());
var oldDate = new Date(ev.date);
var newDate = new Date();
newDate.setDate(oldDate.getDate() + days);
secondDate.val(newDate.getDate()+"/"+newDate.getMonth()+1)+"/"+newDate.getFullYear());
secondDate.datetimepicker('update');
});
var secondDate = $('#secondDate').datetimepicker(pickerOptsGeneral);