web开发中,我们经常遇到客户要显示第几周的等等麻烦的计算,那么输入当前日期如何快速查处是第几周呢?
let date = new Date('2021-02-28') getWeekInYear(date) function getWeekInYear(date) { console.log(date) //判断该星期是否跨年,如果跨年就是第一周 let weekStartDate = getWeekStartByDate(date) //一周开始时间 console.log(weekStartDate,'weekStartDate') let endDate = getDateFromDay(weekStartDate, 6) //一周结束时间 console.log(endDate,'endDate') if (weekStartDate.getFullYear() != endDate.getFullYear()) { console.log(endDate.getFullYear() + '年第1周') let num = 1 return num } let d1 = new Date(date) let d2 = new Date(date) d2.setMonth(0) d2.setDate(1) d2 = getWeekStartByDate(d2) console.log(d2,'d2') let rq = d1 - d2 let days = Math.ceil(rq / (24 * 60 * 60 * 1000)) + 1 let num = Math.ceil(days / 7) console.log(endDate.getFullYear() + '年第' + num + '周') return num } function getWeekStartByDate(date) { let day = date.getDay() return getDateFromDay(date, -day) } function getDateFromDay(dayDate, day) { let date = new Date() date.setTime(dayDate.getTime() + day * 24 * 60 * 60 * 1000) return date }