<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>获取当前时间所在周的日期</title>
<script>
//优化整合以后的代码
function displayDate02(){
var date = new Date();
var year = date.getFullYear();
var mouths = date.getMonth()+1;
var day = date.getDate();
var weekDay = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
document.getElementById("demo").innerHTML="今天是:"+year+"-"+mouths+"-"+day+ " " + weekDay[date.getDay()];
var dayArr = [];
//console.log( weekDay.indexOf( weekDay[date.getDay()] ) );//"星期六"
var _index = weekDay.indexOf( weekDay[date.getDay()] ) ;
if(7 - _index > 1 && 7 - _index < 7){
//当前时间以前的天数
for(var i=0;i< _index;i++){
var beforeday = new Date( new Date().getTime() - 1000 * 60 * 60 * 24 * i );
var _formatbeforeday = beforeday.getFullYear()+"-" + (((beforeday.getMonth() + 1) >= 10) ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth() + 1))+"-" + ((beforeday.getDate() >= 10) ? beforeday.getDate() : "0" + beforeday.getDate());
//console.log(_formatbeforeday);
dayArr.push(_formatbeforeday);
}
//当前时间以后的天数
for(var i=0;i< 7-_index;i++){
var afterday = new Date( new Date().getTime() + 1000 * 60 * 60 * 24 * (7 - _index - i) );
var _formatafterday = afterday.getFullYear()+"-" + (((afterday.getMonth() + 1) >= 10) ? (afterday.getMonth() + 1) : "0" + (afterday.getMonth() + 1))+"-" + ((afterday.getDate() >= 10) ? afterday.getDate() : "0" + afterday.getDate());
//console.log(_formatafterday);
dayArr.push(_formatafterday);
}
document.getElementById("demo2").innerHTML="本周的日期为:"+ dayArr.sort(); //.reverse()反转排序
}
else if(7 - _index == 7){
for(var i=0;i< 7-_index;i++){
var beforeday = new Date( new Date().getTime() - 1000 * 60 * 60 * 24 * i );
var _formatday = beforeday.getFullYear()+"-" + (((beforeday.getMonth() + 1) >= 10) ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth() + 1))+"-" + ((beforeday.getDate() >= 10) ? beforeday.getDate() : "0" + beforeday.getDate());
//console.log(_formatday);
dayArr.push(_formatday);
}
//console.log(dayArr);
document.getElementById("demo2").innerHTML="本周的日期为:"+ dayArr.sort();
}
else{
alert("数据异常");
}
}
</script>
</head>
<body onload="displayDate02()">
<p id="demo"></p>
<p id="demo2"></p>
</body>
</html>
共同学习,写下你的评论
评论加载中...
作者其他优质文章