有故事的本周今天
这是一篇讲述如何通过今天(当天)日期,推导出当天所在一周的日期范围。亦是当天所属周是从哪开始到哪结束的!
由于天色已晚,便直接贴代码,如下如示:
//The following is the code
let currentDate,currentDay,weekDay,startWeekDay,endWeekDay,beforeDay,afterDay;
// 获取当前日期&时间
currentDate = new Date();
// 获取今天几号
currentDay = currentDate.getDate();
// 获取今天星期几
weekDay = currentDate.getDay();
// 计算出当前周几与周一及周日各相隔了几天
if(weekDay <= 0){
beforeDay = 6;
afterDay = 0
}else{
beforeDay = weekDay - 1;
afterDay = 7 - weekDay;
}
//今年第几周FUN
let getWeek = (date) =>{
const DATE = date;
let date_1 = new Date(date);
let date_2 = new Date(date);
date_2.setMonth(0);
date_2.setDate(1);
let rq = date_1 - date_2;
let days = Math.ceil(rq/(24*60*60*1000));
let num = Math.ceil(days/7);
return console.log(""+DATE.getFullYear()+"年第"+num+"周");
}
// 一周开始的日期&一周结束的日期FUN
let WeekDayIntervalFun = (startDate,endDate) =>{
const STARTDATE = startDate, ENDDATE = endDate;
endWeekDay = new Date(currentDate.setDate(currentDay+ENDDATE));
startWeekDay = new Date(currentDate.setDate(currentDay-STARTDATE));
getWeek(currentDate);
formatTimeFun(startWeekDay,'本周周一的日期:');
formatTimeFun(endWeekDay,'本周周日的日期:');
}
//格式化时间FUN(YYYY/MM/DD)
let formatTimeFun = (date,txt) =>{
const DATE = date, TXT = txt;
let nowDateYear = DATE.getFullYear();// 年份,注意必须用getFullYear
let nowDateMonth = DATE.getMonth()+1;// 月份,注意是从0-11
let nowDateDay = DATE.getDate();// 日期
let nowDateDayArry = [nowDateYear,nowDateMonth,nowDateDay];
console.log(TXT+nowDateDayArry.join('/'));
}
WeekDayIntervalFun(beforeDay,afterDay);
最终结果,如下如示:
本文到此就END了~