使用moment.js将天转换为月,将剩余天转换为

时间:2019-08-07 05:52:53

标签: javascript node.js momentjs

例如,我有250天,我想使用moment.js将其转换为几个月和几天,那么您是否知道该怎么做?

Example:

What I've: 250 Days

What I want: 8 Months and 7 Days

3 个答案:

答案 0 :(得分:2)

您可以分别检查年份月份和日期之间的时差并一起显示

var start = moment();
var end = moment().add(250, 'days');

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');

console.log(years + ' years ' + months + ' months ' + days + ' days');
<script src="https://cdn.jsdelivr.net/momentjs/2.10.6/moment-with-locales.min.js"></script>

答案 1 :(得分:2)

您可以立即使用diff and duration来实现此目的。

const currentDate = moment(new Date(), 'YYYY-MM-DD');
const futureDate = moment(currentDate).add(250, 'days');
const diff = moment.duration(futureDate.diff(currentDate));

console.log(`${diff.months()} Months and ${diff.days()} Days`);
// 8 Months and 6 Days

答案 2 :(得分:1)

const futureDate = moment().add(250, 'days');
const duration = moment.duration(futureDate.diff(moment()));

console.log(`${duration.months()} Months and ${duration.days()} Days`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

  

注意:这是一个没有边缘情况的简化示例