到今年为止的每月的一个日期

时间:2018-10-22 09:32:39

标签: javascript jquery date

我已经用Javascript构建了一个小函数来获取到今年的每个月的日期。但是,它有一个循环并导致Chrome崩溃。

function getMonthsInYearTillNow() {
  var today = new Date();
  today = new Date(today.setHours(today.getHours(), 0, 0, 0));
  today_year = today.getFullYear();
  var months = [];

  while (today.getFullYear() === today_year) {
    console.log(today);
    var begin = today;
    begin = new Date(begin.setDate(1));
    begin = new Date(begin.setHours(0, 0, 0, 0));
    var end = today;
    end = new Date(end.setMonth(end.getMonth() + 1));
    end = new Date(end.setDate(0));
    end = new Date(end.setHours(23, 59, 59, 59));
    var cacheobj = {
      'date': today,
      'begin': begin,
      'end': end
    };
    months.push(cacheobj);
    today = new Date(today.setMonth(today.getMonth() - 1, 1));
  }
  return months;
}

也许有人会看到错误。我找不到预先感谢。

编辑:我想要一个数组,其中包含当前年份每个月直到今天的日期对象。换句话说,从2018年1月1日至今(10月18日),例如:

Array[Date-Object(October),Date-Object(September),..,Date-Object(January)]

我在while循环结束时使用

更改var“今天”
today = new Date(today.setMonth(today.getMonth() - 1, 1));

我还有其他三个函数可用于不同类型的时间范围,并且它们都能正常工作,这就是为什么我很困惑并且找不到解决方法的原因:/

4 个答案:

答案 0 :(得分:0)

根据您的代码,执行today.getFullYear() === today_year与执行while true === true相同,这使您的代码可以无限次运行

您可以执行以下操作以获得结果:

function getMonthsInYearTillNow() {
  let i = 0;
  const result = [];
  let isCurrentMonth = false;
  while (!isCurrentMonth) {
    let cacheobj = {
      'begin': new Date(2018, i, 1),
      'end': new Date(2018, i, 1, 23, 59, 59, 59)
    };
    result.push(cacheobj);
    if (i === new Date().getMonth()) {
      isCurrentMonth = true;
    }
    i++;
  };
  return result;
}
console.log(getMonthsInYearTillNow());

答案 1 :(得分:0)

很抱歉给您打发时间。 我只是将while转换为for循环,就是这样。

function getMonthsInYearTillNow() {
        var today = new Date();
        today = new Date(today.setHours(today.getHours(), 0, 0, 0));
        today_year = today.getFullYear();
        var months = [];
        for (var i = today.getMonth(); i >= 0; i--) {
            today = new Date(today.setMonth(i,1));
            console.log(today);
            var begin = today;
            begin = new Date(begin.setDate(1));
            begin = new Date(begin.setHours(0,0,0,0));
            var end = today;
            end = new Date(end.setMonth(end.getMonth() + 1));
            end = new Date(end.setDate(0));
            end = new Date(end.setHours(23,59,59,59));
            var cacheobj = {'date': today, 'begin': begin, 'end': end};
            months.push(cacheobj);
        }
        return months;
    }

感谢您的时间和烦恼:)

答案 2 :(得分:0)

这个更具说明性。

const monthNameShort = (month) => month.substring(0, 3);
const getMonthFromString = (monthName) => {
  const date = new Date(Date.parse(monthName + 1, new Date().getFullYear()));
  const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
  const month = new Date(Date.parse(monthName + 1, new Date().getFullYear())).getMonth() + 1;

  return {
    lastDay,
    month
  };
}

function getMonthsInYearTillNow() {
  const monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];
  const today = new Date();
  const current_month = today.getMonth();

  return Array.from({
      length: current_month - 1
    })
    .map((_, index) => getMonthFromString(monthNameShort(monthNames[index])))
    .reduce((acc, cur) => {
      acc = {
        dayleft: acc.dayleft + cur.lastDay,
        months: [...acc.months, {
          name: monthNames[cur.month - 1],
          days: cur.lastDay
        }]
      }

      return acc;
    }, {
      dayleft: today.getDate(),
      months: []
    });
}

console.log(getMonthsInYearTillNow())

答案 3 :(得分:0)

使用Array.from

const now = new Date();

const year = now.getFullYear(); // Get the year

const month = now.getMonth() + 1; // Get the month

const months = Array.from(Array(month), (_, i) => new Date(year, i, 1));

console.log(months);