【问题标题】:One date per month of current year till now当年至今每月一个日期
【发布时间】:2018-10-23 10:35:59
【问题描述】:

我用 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 月到现在(10 月 18 日),例如:

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

我在 while 循环结束时更改了 var 'today'

today = new Date(today.setMonth(today.getMonth() - 1, 1));

我为不同类型的时间范围提供了三个其他功能,它们都可以工作,这就是为什么我很困惑并且找不到解决方案:/

【问题讨论】:

  • 因为循环无限而崩溃;您永远不会更改 while 条件中的任何一个年份值。您要达到的输出是什么?我确信它可以以更简单的方式完成
  • 感谢编辑,但仍不清楚。您是否想要从现在开始为接下来的 12 个月(即 Oct-18 到 Sep-19)或当年剩余月份(即 Oct-18、Nov-18 和 Dec-18)的一系列值。您的示例在 1 月结束,鉴于描述,这毫无意义。
  • @RoryMcCrossan 对不起.. :/ 我想要今年过去几个月的值数组。例如10 月 18 日、9 月 18 日、8 月 18 日等。换句话说:从 2018 年 1 月到现在。

标签: javascript jquery date


【解决方案1】:

对不起,各位。。 我只是将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】:

这个更具声明性。

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】:

    根据您的代码,执行 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());
    

    【讨论】:

    • Downvote 不是我的,但这只是描述了问题,并没有通过提供解决方案来回答它。
    • 您到底在寻找什么结果?
    • 你需要问 OP,而不是我。虽然请注意我已经在 cmets 中有。我建议在 OP 明确他们正在尝试做什么之前删除它。
    • 感谢您的回答,但在我看来,这个解决方案每天都可以节省吗?我只想要一个月的一天。简化第 1 天。
    • 语义上,将 const 用于 const result = []const cacheobj = {...}; 没有意义。当然你不能分配不同的数组或对象,但是数组和对象在执行过程中都会发生变化,这与常量的概念相反。 ;-)
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多