我的代码中有三个<input>标记,其中两个是从<input>中选择的日期填充的。
<input id="from-date" type="text" class="form-control" placeholder="From">
<input id="to-date" type="text" class="form-control" placeholder="To">
<input id="total-count" class="form-control" placeholder="Total no. of Years, Months and Days.">我想用年、月和日来计算这两个日期之间的差异,并在total-count中显示。我看了一些关于Stack溢出的例子,无法实现/找到一个理想的解决方案,因为它真的让我感到困惑。如果有人能帮我解决这个问题,那会有很大帮助的。
下面是我的JS代码。我更新了整个代码这里
$(function() {
// create the from date
$('#from-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
}).on('changeDate', function(ev) {
ConfigureToDate();
});
$('#to-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
startDate: $('#from-date').val()
});
// Set the min date on page load
ConfigureToDate();
// Resets the min date of the return date
function ConfigureToDate() {
$('#to-date').val("").datepicker("update");
$('#to-date').datepicker('setStartDate', $('#from-date').val());
}
}); 发布于 2018-05-13 21:19:47
如果您使用的是日期,就没有必要重新发明轮子了,Moment.js是一个很好的库。(https://momentjs.com/)
在页面中安装/包括Moment.js,然后:
HTML:
<input id="from-date" type="text" class="form-control" placeholder="From">
<input id="to-date" type="text" class="form-control" placeholder="To">
<input id="total-count" class="form-control" placeholder="Total no. of Years, Months and Days.">
<br />
<br />
<input id="calculate" type="button" value="Calculate" />JavaScript:
$(function() {
$('#from-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
});
$('#to-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy'
});
$('#calculate').on('click', function() {
var fromDate = moment($('#from-date').val(), 'DD-MM-YYYY');
var toDate = moment($('#to-date').val(), 'DD-MM-YYYY');
if (fromDate.isValid() && toDate.isValid()) {
var duration = moment.duration(toDate.diff(fromDate));
$('#total-count').val( duration.years() + ' Year(s) ' + duration.months() + ' Month(s) ' + duration.days() + ' Day(s)');
} else {
alert('Invalid date(s).')
}
});
});JSFiddle: (http://jsfiddle.net/cvh2u2bk/)
发布于 2018-05-13 20:11:59
您可以使用这个概念:
var date1 = new Date("7/13/2010");
var date2 = new Date("12/15/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var days = Math.floor(timeDiff / (1000 * 3600 * 24));
var months = Math.floor(days / 31);
varyears = Math.floor(months / 12);希望这能帮到你:)
发布于 2018-05-13 23:41:00
使用日期--我建议您使用像动量这样的包,它可以帮助您使用一些日期格式。
var date1 = moment('01/05/2017')
var date2 = moment('01/04/2017')
date1.diff(date2, 'days') //1
date1.diff(date2, 'months')//0
date1.diff(date2, 'years')//0如果要得到确切的差异,可以添加标志变量。
date1.diff(date2, 'months', true)//0.03225806451612903https://stackoverflow.com/questions/50318784
复制相似问题