为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

绝地无双 2022-12-29 09:59:23
我正在寻找一个 JS 库/实用程序/函数,您可以在其中给它指定月数,它会返回它的人类可读版本。我几乎已经在 Vanilla JS 中完成了,但现在我发现有很多边缘情况我不想重新发明轮子。例子func(3) => "3 Months"func(1) => "1 Month" // singularfunc(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问题陈述:我不想重新发明轮子,看看有没有像上面那样目前正在做日期转换的库。
查看完整描述

3 回答

?
慕桂英546537

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>


查看完整回答
反对 回复 2022-12-29
?
拉丁的传说

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

越简单越好,特别是当它是一个如此简单的问题时。您不想为此使用库来膨胀您的应用程序。




查看完整回答
反对 回复 2022-12-29
?
慕神8447489

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>

//img1.sycdn.imooc.com//63acf4af0001fc7221111235.jpg

也看看https://github.com/codebox/moment-precise-range


查看完整回答
反对 回复 2022-12-29
  • 3 回答
  • 0 关注
  • 149 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号