为了账号安全,请及时绑定邮箱和手机立即绑定

通过当前时间获取当前所在周的7天的时间

标签:
Html/CSS

<!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> 

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消