根据年、月,获取某年某月的周数及每周对应的开始时间和结束时间。
代码如下:
/*-----获取某年某月每周的开始时间和结束时间-----*/
function getInfo(year, month) {
function formatDate(date) {
let myyear = Number(date.getFullYear());
let mymonth = Number(date.getMonth()+1);
let myweekday = Number( date.getDate());
if(mymonth < 10){
mymonth = "0" + mymonth;
}
if(myweekday < 10){
myweekday = "0" + myweekday;
}
return (myyear+"-"+mymonth + "-" + myweekday);
}
let nowMonth=month-1
let startMonth //本月的开始时间
let endMonth //本月的结束时间
//获得某月的天数
function getMonthDays(month){
let monthStartDate = new Date(year, nowMonth, 1);
let monthEndDate = new Date(year, month + 1, 1);
let days = (monthEndDate - monthStartDate)/(1000 * 60 * 60 * 24);
return days;
}
//获得本月的开始日期
function getMonthStartDate(){
let monthStartDate = new Date(year, nowMonth, 1);
return formatDate(monthStartDate);
}
//获得本月的结束日期
function getMonthEndDate(){
let monthEndDate = new Date(year, nowMonth, getMonthDays(nowMonth));
return formatDate(monthEndDate);
}
startMonth=getMonthStartDate()
endMonth=getMonthEndDate()
console.log("本月的开始时间:"+startMonth+"本月的结束时间: "+endMonth)
let d = new Date();//
// what day is first day
d.setFullYear(year, month-1, 1);
let w1 = d.getDay();//某月的第一天是星期几
if (w1 == 0){
w1 = 7;
}
console.log("某月的第一天是星期:" + w1);
let firtWeek_count = 7 - w1 + 1; //第一周有几天
console.log("第一周有几天:" + firtWeek_count);
// total day of month
d.setFullYear(year, month, 0);
let dd = d.getDate();//某月的总天数
console.log("某月的总天数:" + dd);
// let mydate=new Date(year,month-1,dd);
// let end1=mydate.getDay(); //某月的最后一天的星期
// console.log("某月的总天数:" + end1);
let d1
// first Monday
if (w1 != 1){//第一天不是星期一
d1 = 7 - w1 + 2;
}
else {
d1 = 1;
}
let week_count = Math.ceil((dd-d1+1)/7);
if(w1 == 1){
week_count= week_count;
}else{
week_count= week_count+1;
}
console.log(year + "年" + month + "月有" + week_count +"周");
for (let i = 0; i < week_count; i++) {
let monday = firtWeek_count + (i-1)*7+1;
// let monday =i*7-1;
let sunday = monday + 6;
let startTime = year+"/"+month+"/"+monday;
let endTime;
if(i==0){
startTime=startMonth;
endTime = year+"/"+month+"/"+firtWeek_count;
}
else if(i == week_count-1){
startTime=year+"/"+month+"/"+(firtWeek_count + (week_count - 2) * 7+1);
// startTime=year+"/"+month+"/"+(dd-end1+1);
endTime = endMonth;
}
else{
endTime = year+"/"+month+"/"+sunday;
}
console.log("第"+(i+1)+"周 从" + startTime + " 到 " + endTime + "");
}
}
getInfo(2020,3);
运行结果:
参考:https://blog.csdn.net/qq_37899792/article/details/90751791?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-9&utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-9