根據具體日期計算是一年的第幾周:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
// 計算具體日期爲當月的第幾周
function getWeek(str) {
// 將字符串轉爲標準時間格式
str = Date.parse(str);
str = new Date(str);
// 先計算出該日期爲第幾周
let week = Math.ceil(str.getDate()/7);
let month = str.getMonth() + 1;
// 判斷這個月前7天是周幾,如果不是週一,則計入上個月
if (str.getDate() < 7) {
if (str.getDay() !== 1) {
week = 5;
month = str.getMonth();
}
}
console.log(`${month}-${week}`);
}
console.log(getWeek('2017-01-01'));
</script>
</body>
</html>
根據具體日期計算是當月的第幾周:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
const year = String(new Date(Date.parse(date)).getFullYear());
console.log('year:', year);
console.log('date:', new Date(year));
const week = (((new Date(date)) - (new Date(year))) / (24 * 60 * 60 * 7 * 1000) | 0) + 1;
console.log('week', week);
</script>
</body>
</html>