有必要计算两个时刻之间的时间间隔,并以{...年......月......天......小时......分钟}的格式显示。我使用以下代码:
var start = moment("2016-05-04 13:00:00");
var end = moment("2018-05-04 13:00:00");
var diff = moment(end).diff(start);
var duration = moment.duration(diff);
var years = duration.years();
var months = duration.months();
var days = duration.days();
var hours = duration.hours();
var minutes = duration.minutes();
console.log(years + " years " +
months + " months " +
days + " days " +
hours + " hours " +
minutes + " minutes ");
<script src="https://momentjs.com/downloads/moment.js"></script>
我期待结果“2年0个月0天0小时0分”,但是“1年11个月29天0小时0分”。请告诉我这是什么问题?
答案 0 :(得分:0)
也许这对其他人有用。下一个代码(来自回答Moment.js - Get difference in two birthdays in years, months and days)帮助解决了这个问题:
var start = moment("2016-05-04 13:00:00");
var end = moment("2018-05-04 13:00:00");
var years = end.diff(start, 'year');
start.add(years, 'years');
var months = end.diff(start, 'months');
start.add(months, 'months');
var days = end.diff(start, 'days');
start.add(days, 'days');
var hours = end.diff(start, 'hours');
start.add(hours, 'hours');
var minutes = end.diff(start, 'minutes');
console.log(years + " years " +
months + " months " +
days + " days " +
hours + " hours " +
minutes + " minutes ");
<script src="https://momentjs.com/downloads/moment.js"></script>
它也适用于其他日期。