let dates = ["2019-01-01","2021-02-28","2020-05-01","2020-05-01","2020-01-03","2020-11-02","2020-10-02","2020-01-02"]
//冒泡排序
for (let i = 0; i < dates.length; i++) {
for (let j = 0; j < dates.length-i-1; j++) {
if (new Date(dates[j]).getTime()>new Date(dates[j+1]).getTime()) {
let a = dates[j]
dates[j] = dates[j+1];
dates[j+1] = a;
}
}
}
let months = [];
let days = [];
/**
* 获取月份
* @param {Object} minDate 最小时间 yyyy-MM-dd
* @param {Object} maxDate 最大时间 yyyy-MM-dd
*/
function getDiffDate(minDate,maxDate){
let startDate = new Date(minDate);
let endDate = new Date(maxDate);
//把时间的天数都设置成当前月第一天
startDate.setDate(1)
endDate.setDate(1)
// new Date(yyyy-MM-dd) 不知为何有时候小时是 08 有时候是00
endDate.setHours(0)
startDate.setHours(0)
while (endDate.getTime()>=startDate.getTime()){
let year = startDate.getFullYear();
let month = startDate.getMonth()+1;
//加一个月
startDate.setMonth(month)
if (month.toString().length == 1) {
month = "0" + month;
}
months.push(year+"-"+month)
}
}
getDiffDate(dates[0],dates[dates.length-1])
console.log(months)
console.log(dates)
/**
* 获取天数
* 获取区间的所有日期
* @param {Object} start
* @param {Object} end
*/
function getDays (minDate, maxDate) {
let startDate = new Date(minDate);
let endDate = new Date(maxDate);
while (endDate.getTime() >= startDate.getTime()) {
let year = startDate.getFullYear();
let month = startDate.getMonth()+1
let day = startDate.getDate()
//加一天
startDate.setDate(day + 1);
if (month.toString().length == 1) {
month = "0" + month;
}
if (day.toString().length == 1) {
day = "0" + day;
}
days.push(year + "-" + month + "-" + day);
}
}
getDays("2020-11-12","2021-01-01")
console.log(days)
下面方法获取指定月份有多少天, 转自(侵删):https://www.cnblogs.com/wisewrong/p/7494867.html
/**
* 获取指定月份有多少天
* @param {Object} date yyyy-MM-dd
*/
function getMonthLength(date) {
// 将日期设置为下月一号
d.setMonth(d.getMonth()+1)
d.setDate('1')
// 获取本月最后一天
d.setDate(d.getDate()-1)
return d.getDate()
}