以下内容将给我数年和数月:
var years = toDate.diff(todaysDate, 'years');
var months = toDate.diff(todaysDate, 'months');
所以如果差异是2年零2个月,我会得到:
2
14
我可以用时间来获得这种格式的差异吗?
2 years, 2 months
答案 0 :(得分:1)
由于您不想添加其他插件,因此可以使用模数运算符%
将月份转换为正确的值。
这是一个工作示例:
var todaysDate = moment();
var toDate = moment().add(14, 'months');
var years = toDate.diff(todaysDate, 'years');
var months = toDate.diff(todaysDate, 'months');
console.log(years + ' years, ' + months % 12 + ' months');
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
使用moment-duration-format的另一个解决方案如下:
var todaysDate = moment();
var toDate = moment().add(14, 'months');
var months = toDate.diff(todaysDate, 'months');
var duration = moment.duration(months, 'months');
console.log(duration.format("y [years] M [months]"));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
通过这种方式,您可以从月份值创建持续时间对象,然后根据需要使用插件对其进行格式化。
答案 1 :(得分:0)
不是暂时的。我知道他们正在使用插件来格式化持续时间,但不要指望它很快就会被释放。