整理:

如果需要获取最近若干个月,牵扯到跨年的话,该怎么实现的问题,抽了点时间,代码如下:

    /**纪元时间获取最近12个月
     *
     * @num 传入获取月的数目
     **/
    (function getMonth(num) {
        var _curDate = new Date(),
            _curTime = _curDate.getTime(), //当前纪元时间
            _oneDayTime = 24 * 3600 * 1000, //一天的总毫秒数
            _thisMonSumDay = new Date(_curDate.getFullYear(), _curDate.getMonth() + 1, 0).getDate(); //当前月份总天数
        var _resultArr = [];
        for (var i = 1, j = _curTime; i <= num; i++, j -= _thisMonSumDay * _oneDayTime) {
            //月迭代
            if (_resultArr.length >= num) {
                break;
            }
            //当月里的时间点,作为当月依据
            var _thisMonth = new Date(j);
            //重新赋值当前月天数
            _thisMonSumDay = new Date(_thisMonth.getFullYear(), _thisMonth.getMonth() + 1, 0).getDate();
            _resultArr.push(DateFormat("yyyy-MM", new Date(j)));
        }
        return _resultArr;
    })(38);

欢迎各种拍砖

相关文章:

  • 2022-12-23
  • 2021-11-29
  • 2022-12-23
  • 2021-05-25
  • 2021-06-15
  • 2021-12-20
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-07
  • 2022-02-13
  • 2022-12-23
  • 2021-09-06
  • 2021-10-15
相关资源
相似解决方案