如何遍历出全部的月份

比如说我的是“2017-01”和“2017-05”
我想遍历输出全部的月份,怎样写才能输出
["2017-01","2017-02","2017-03","2017-04","2017-05"]
还有就是存在跨年的情况例如“2017-11”和“2018-03”
怎样输出
["2017-11","2017-12","2018-01","2018-02","2018-03"]

拉莫斯之舞
浏览 846回答 1
1回答

MYYA

// 转换为时间戳var startTime = new Date("2017-11").getTime();var endTime = new Date("2018-03").getTime();// 存放结果var arr = []// 最后的格式转换var format&nbsp; = function(time) {&nbsp; &nbsp; var date = new Date(time)&nbsp; &nbsp; return date.getFullYear() + '-' + (date.getMonth() + 1)}// 判断是否为闰年var isLeapYear = function(year) {&nbsp; return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0)&nbsp; }// 月份映射 假设不为闰年var MONTH = {&nbsp; &nbsp; '1': 31,&nbsp; &nbsp; '2': 28,&nbsp; &nbsp; '3': 31,&nbsp; &nbsp; '4': 30,&nbsp; &nbsp; '5': 31,&nbsp; &nbsp; '6': 30,&nbsp; &nbsp; '7': 31,&nbsp; &nbsp; '8': 31,&nbsp; &nbsp; '9': 30,&nbsp; &nbsp; '10': 31,&nbsp; &nbsp; '11': 30,&nbsp; &nbsp; '12': 31}arr.push("2017-11")while (startTime < endTime) {&nbsp; &nbsp; // 转换时间格式&nbsp; &nbsp; var start = new Date(startTime)&nbsp; &nbsp; // 判断是否为闰年的2月份&nbsp; &nbsp; if (isLeapYear(start.getFullYear()) && (start.getMonth() + 1 === 2)) {&nbsp; &nbsp; &nbsp; &nbsp; startTime = startTime + 29 * 24 * 60 * 60 * 1000&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; // 其他情况&nbsp; &nbsp; &nbsp; &nbsp; startTime = startTime + MONTH[start.getMonth() + 1] * 24 * 60 * 60 * 1000&nbsp; &nbsp; }&nbsp; &nbsp; arr.push(format(startTime))}arr.push("2018-03")console.log(arr)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript