const endTime = 1680451199000
// 过去6个月每个月1号凌晨时间戳数组
let monthArr = getLastMonth(endTime, 6, "number")
const startMonthTime = monthArr[0]
const endMonthTime = getMonthEnd(monthArr[5]).monthEnd
let monthList = []
monthArr.map(item => {
monthList.push(getMonthEnd(item))
})
console.log(monthList)
// 获取最近六个月每个月的1号(time - 时间, num - 想要获取的月份, type - string/number)
function getLastMonth(time, num, type) {
let data = new Date(time);
//获取年
let year = data.getFullYear();
//获取月
let mon = data.getMonth() + 1;
let arry = []
for (let i = 0; i < num; i++) {
if (mon <= 0) {
year = year - 1;
mon = mon + 12;
}
if (mon < 10) {
mon = "0" + mon;
}
if (type === "string") {
arry[i] = year + "-" + mon + "-01 00:00:00";
} else {
arry[i] = new Date(year + "-" + mon + "-01 00:00:00").valueOf()
}
mon = mon - 1;
}
arry = arry.sort((a, b) => a - b)
return arry;
}
// 获取某个时间的月首和月尾信息
function getMonthEnd(times) {
let date = new Date(times);
let new_year = date.getFullYear(); //取当前的年份
let month = date.getMonth();
let new_month = month + 1;//取当前的月份
if (month > 12) {
new_month -= 12; //月份减
new_year++; //年份增
}
let d = new Date(new_year, new_month, 1);//取当年当月中的第一天
let lastDay = new Date(d.getTime() - 1000 * 60 * 60 * 24).getDate();//获取当月最后一天日期
let mon = date.getMonth() + 1
if (mon < 10) {
mon = "0" + mon
}
let start = d.getFullYear() + '-' + mon + '-' + "0" + d.getDate() + ' ' + "00" + ':' + "00" + ':' + "00";
let end = d.getFullYear() + '-' + mon + '-' + lastDay + ' ' + 23 + ':' + 59 + ':' + 59;
return {
monthStart: new Date(start).valueOf(),
monthStartText: start,
monthEnd: new Date(end).valueOf(),
monthEndText: end
}
}
console