以下内容将为我提供几年和几个月:
var years = toDate.diff(todaysDate, 'years');
var months = toDate.diff(todaysDate, 'months');
如果相差 2 年零 2 个月,我会得到:
2
14
我可以使用 moment 来获得这种格式的差异吗?
2 years, 2 months
最佳答案
由于您不想添加额外的插件,因此可以使用模运算符 %
将月份转换为正确的值。
这是一个工作示例:
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>
通过这种方式,您可以根据月份值创建一个持续时间对象,然后使用插件根据您的需要对其进行格式化。
关于javascript - 我可以使用 momentjs 获取两个日期之间以年和月为单位的差异吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39274143/