3 回答

TA貢獻1848條經驗 獲得超10個贊
使用moment.js:
Date.getFormattedDateDiff = function (date1, date2) {
var b = moment(date1),
a = moment(date2),
intervals = ['year', 'month', 'week', 'day'],
out = [];
for (var i = 0; i < intervals.length; i++) {
var diff = a.diff(b, intervals[i]);
b.add(diff, intervals[i]);
if (diff == 0)
continue;
out.push(diff + ' ' + intervals[i] + (diff > 1 ? "s" : ""));
}
return out.join(', ');
};
function OutputMonths(months) {
var newYear = new Date(new Date().getFullYear(), 0, 1);
var days = (months % 1) * 30.4167;
var newDate = new Date(newYear.getTime());
newDate.setMonth(newDate.getMonth() + months);
newDate.setDate(newDate.getDate() + days);
console.log('Number of months: ' + Date.getFormattedDateDiff(newYear, newDate));
}
OutputMonths(3);
OutputMonths(1);
OutputMonths(0.1);
OutputMonths(0.25);
OutputMonths(13);
OutputMonths(14);
OutputMonths(14.25);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

TA貢獻1789條經驗 獲得超8個贊
這取決于您的“人類可讀版本”版本是什么。您可以簡單地將您的月份數字轉換為天數并從那里開始工作。由于您在示例案例中包含了年、月和周,因此您所需要的就是這個。
function func(months) {
let days = months * 30.5; // Average days in a month
let y = 0, m = 0, w = 0;
while (days >= 365) {y++;days -= 365;}
while (days >= 30.5) {m++;days -= 30.5;}
while (days >= 7) {w++;days -= 7;}
let out =
(y ? (`${y} Year` + (y > 1 ? "s " : " ")) : "") +
(m ? (`${m} Month` + (m > 1 ? "s " : " ")) : "") +
(w ? (`${w} Week` + (w > 1 ? "s " : " ")) : "");
console.log(out);
}
func(10);
func(3);
func(1);
func(0.1);
func(0.25);
func(13);
func(14);
func(14.25);
越簡單越好,特別是當它是一個如此簡單的問題時。您不想為此使用庫來膨脹您的應用程序。

TA貢獻1780條經驗 獲得超1個贊
console.log(moment.duration(40, 'months').toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
也看看https://github.com/codebox/moment-precise-range
添加回答
舉報