日期可能很难处理,但是
moment
图书馆使它容易得多。在我的示例中,我获取这两个字段的输入,将它们解析为一个moment对象,并计算它们在持续时间内的差异。您可以在
Moment.js docs
.
代码段的差异以天表示。如果要将其更改为月或年,请更新下面的行。
log(Math.round(duration.as('days')) + 'days');
这是一个工作日的例子。
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var yearSelect = document.querySelector('#year_select').value;
var newDate = document.querySelector('#new_date').value;
var first_date = new window.moment('31-03-' + yearSelect, 'DD-MM-YYYY');
var second_date = new window.moment(newDate, 'YYYY-MM-DD');
if(yearSelect.length !== 4 || newDate === '') {
log('');
return;
}
var duration = window.moment.duration(first_date.diff(second_date));
log(Math.round(duration.as('days')) + 'days');
}
function log(value) {
var answer = document.querySelector('#answer');
answer.value = value;
}
<script src="https://cdn.jsdelivr.net/momentjs/2.10.6/moment-with-locales.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
关于如何设置日期/持续时间的格式有一些讨论,例如。
1年2个月5天
. 如果你想要这样的东西,在这些讨论中看看一个可能的解决方案。