转:JS获取前七天的日期
2018-10-10 19:59 马尔代夫_珍 阅读(350) 评论(0) 编辑 收藏 举报<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>时间</title>
</head>
<body>
<script>
function getBeforeDate(n) {
var n = n;
var d = new Date();
var year = d.getFullYear();
var mon = d.getMonth() + 1;
var day = d.getDate();
if (day <= n) {
if (mon > 1) {
mon = mon - 1;
}
else {
year = year - 1;
mon = 12;
}
}
d.setDate(d.getDate() - n);
year = d.getFullYear();
mon = d.getMonth() + 1;
day = d.getDate();
s = year + "-" + (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
return s;
}
console.log(getBeforeDate(1));//昨天的日期
console.log(getBeforeDate(2));
console.log(getBeforeDate(3));
console.log(getBeforeDate(4));
console.log(getBeforeDate(5));
console.log(getBeforeDate(6));
console.log(getBeforeDate(7));//前七天的日期
</script>
</body>
</html>