给定月份的 Javascript 返回时间字符串

我正在寻找一个 JS 库/实用程序/函数,您可以在其中给它指定月数,它会返回它的人类可读版本。


我几乎已经在 Vanilla JS 中完成了,但现在我发现有很多边缘情况我不想重新发明轮子。


例子


func(3) => "3 Months"

func(1) => "1 Month" // singular

func(0.1) => "1 Week"

func(0.25) => "2 Weeks"

func(13) => "1 year and 1 month"

func(14) => "1 year and 2 months"

func(14.25) => "1 year, 2 months and two weeks"

.

..

...etc

问题陈述:我不想重新发明轮子,看看有没有像上面那样目前正在做日期转换的库。


绝地无双
浏览 150回答 3
3回答

慕桂英546537

使用moment.js:Date.getFormattedDateDiff = function (date1, date2) {&nbsp; var b = moment(date1),&nbsp; &nbsp; a = moment(date2),&nbsp; &nbsp; intervals = ['year', 'month', 'week', 'day'],&nbsp; &nbsp; out = [];&nbsp; for (var i = 0; i < intervals.length; i++) {&nbsp; &nbsp; var diff = a.diff(b, intervals[i]);&nbsp; &nbsp; b.add(diff, intervals[i]);&nbsp; &nbsp; if (diff == 0)&nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; out.push(diff + ' ' + intervals[i] + (diff > 1 ? "s" : ""));&nbsp; }&nbsp; return out.join(', ');};function OutputMonths(months) {&nbsp; var newYear = new Date(new Date().getFullYear(), 0, 1);&nbsp; var days = (months % 1) * 30.4167;&nbsp; var newDate = new Date(newYear.getTime());&nbsp; newDate.setMonth(newDate.getMonth() + months);&nbsp; newDate.setDate(newDate.getDate() + days);&nbsp; 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>

拉丁的传说

这取决于您的“人类可读版本”版本是什么。您可以简单地将您的月份数字转换为天数并从那里开始工作。由于您在示例案例中包含了年、月和周,因此您所需要的就是这个。function func(months) {&nbsp; &nbsp; let days = months * 30.5; // Average days in a month&nbsp; &nbsp; let y = 0, m = 0, w = 0;&nbsp; &nbsp; while (days >= 365) {y++;days -= 365;}&nbsp; &nbsp; while (days >= 30.5) {m++;days -= 30.5;}&nbsp; &nbsp; while (days >= 7) {w++;days -= 7;}&nbsp; &nbsp; let out =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; (y ? (`${y} Year` + (y > 1 ? "s " : " ")) : "") +&nbsp; &nbsp; &nbsp; &nbsp; (m ? (`${m} Month` + (m > 1 ? "s " : " ")) : "") +&nbsp; &nbsp; &nbsp; &nbsp; (w ? (`${w} Week` + (w > 1 ? "s " : " ")) : "");&nbsp; &nbsp; console.log(out);}func(10);func(3);func(1);func(0.1);func(0.25);func(13);func(14);func(14.25);越简单越好,特别是当它是一个如此简单的问题时。您不想为此使用库来膨胀您的应用程序。

慕神8447489

console.log(moment.duration(40,&nbsp;'months').toISOString());<script&nbsp;src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>也看看https://github.com/codebox/moment-precise-range
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript