首页 > 解决方案 > 给定月份的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

问题陈述:我不想重新发明轮子,看看是否有任何图书馆目前正在进行上述日期转换。

标签: javascript

解决方案


使用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>


推荐阅读