评论有小伙伴提出周日的时候获取的不对,我自己后来也发现了,周日的时候会获取到下周 周一-周日的日期,主要是date默认的一周是周日-周六,所以周日的时候date.getDay()获取到的是本周的第一天,而我的逻辑是按照周一--周日,所以本周日的时候会获取了下周一--下周日的日期
有需要的小伙伴可以按照下面调整一下逻辑为周日--周六为一周就没问题了
getCurrentDay(currentDate) {
let thisweek = {}
let thisMonth = {}
let thisYear = {}
let date = new Date();
// 本周一的日期
date.setDate(date.getDate() - date.getDay() + 1);
thisweek.start_day = date.getFullYear() + "-" + ((date.getMonth() + 1)<10?"0"+(date.getMonth() + 1):(date.getMonth() + 1)) + "-" + (date.getDate()<10?"0"+date.getDate():date.getDate()) ;
// 本周日的日期
date.setDate(date.getDate() - date.getDay() + 7);
thisweek.end_day = date.getFullYear() + "-" + ((date.getMonth() + 1)<10?"0"+(date.getMonth() + 1):(date.getMonth() + 1)) + "-" + (date.getDate()<10?"0"+date.getDate():date.getDate());
// 本月第一天
date.setDate(1);
thisMonth.start_day = date.getFullYear() + "-" + ((date.getMonth() + 1)<10?"0"+(date.getMonth() + 1):(date.getMonth() + 1)) + "-" + (date.getDate()<10?"0"+date.getDate():date.getDate())
// 本月最后一天
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1 , 0)
thisMonth.end_day = lastDay.getFullYear() + "-" + ((lastDay.getMonth() + 1)<10?"0"+(lastDay.getMonth()+1):(lastDay.getMonth() + 1)) + "-" + (lastDay.getDate()<10?"0"+lastDay.getDate():lastDay.getDate())
// 本年第一天
thisYear.start_day = date.getFullYear() + "-" + "01-01"
// 本年最后一天
thisYear.end_day = date.getFullYear() + "-" + "12-31"
if(currentDate=="本周"){
return thisweek
}else if(currentDate=="本月"){
return thisMonth
}else if(currentDate=="本年"){}
return thisYear
}
百度了n个大神的方法终于整合了这一个方法
再补充一个获取昨天前天的方法
getDate(){
var nowDate = new Date();
var year = nowDate.getFullYear();
var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
let yesterday = year +"-"+ month +"-" + (date-1)
let beforeYesterday = year +"-"+ month +"-" + (date-2)
if(date=="01"){
let day = new Date(nowDate.getFullYear(), nowDate.getMonth(), 0).getDate();
yesterday = year +"-"+ ((month-1)<10?"0" + (month-1):(month-1)) +"-" + day
beforeYesterday = year +"-"+ ((month-1)<10?"0" + (month-1):(month-1)) +"-" + (day-1)
}else if(date=="02"){
let day = new Date(nowDate.getFullYear(), nowDate.getMonth(), 0).getDate();
beforeYesterday = year +"-"+ ((month-1)<10?"0" + (month-1):(month-1)) +"-" + day
}
this.setState({
yesterday: yesterday,
beforeYesterday: beforeYesterday
})
}
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行