我正在寻找如何获得两个月之间的月数和剩余天数。
示例:in = 2017-04-10, out = 2017-05-15
输出应 1个月,5天
-
这是我试过的: 月数
var numofmonths = out_month - in_month + (12 * (out_year - in_year));
if(out_day < in_day){
numofmonths--;
}
和天
var numofdays (end - start) / (1000 * 60 * 60 * 24)
输出就像 1个月,35天。
如果有月份,如何删除当月的日期,并且仅显示剩余的天数?
答案 0 :(得分:0)
以下是使用Moment.js的解决方案:
let getDiff = (inDate, outDate) => {
let years, months, days;
inDate = moment(inDate);
outDate = moment(outDate);
years = outDate.diff(inDate, 'year');
inDate.add(years, 'years');
months = outDate.diff(inDate, 'months');
inDate.add(months, 'months');
days = outDate.diff(inDate, 'days');
return {
days: days,
months: months,
years: years
};
},
getDiffFormatted = d => `${d.years} years, ${d.months} month, ${d.days} days`;
// in = 2017-04-10 and out = 2017-05-15
let diff1 = getDiff('2017-04-10', '2017-05-15');
console.log('diff1:', getDiffFormatted(diff1));
// in = 2017-04-10 and out = 2017-05-09
let diff2 = getDiff('2017-04-10', '2017-05-09');
console.log('diff2:', getDiffFormatted(diff2));
// in = 2017-04-10 and out = 2017-06-15
let diff3 = getDiff('2017-04-10', '2017-06-15');
console.log('diff3:', getDiffFormatted(diff3));
// in = 2015-01-22 and out = 2017-06-15
let diff4 = getDiff('2015-01-22', '2017-06-15');
console.log('diff4:', getDiffFormatted(diff4));
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
&#13;