<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
String.prototype.weekIndexInYear = function () {
var nowDate = new Date(this != '' ? this : new Date());
var initTime = new Date(this != '' ? this : new Date());
initTime.setMonth(0); // 本年初始月份
initTime.setDate(1); // 本年初始时间
initTime.setHours(0);
initTime.setMinutes(0);
initTime.setSeconds(0);
nowDate.setHours(23);
nowDate.setMinutes(59);
nowDate.setSeconds(59);
var differenceVal = nowDate - initTime; // 今天的时间减去本年开始时间,获得相差的时间
var todayYear = Math.ceil(differenceVal / (24 * 60 * 60 * 1000)); // 获取今天是今年第几天
console.log('今年的第几天?',todayYear);
/* 周日为第一周的算法 */
// return Math.ceil(todayYear / 7)
/* 周一为第一周的算法 */
var firstDay = initTime.getDay(); // 获取这年的第一天是周几,因为首周可能是上一年的最后一周内
// console.log('今年第一天是周几',firstDay);
var startDiff;
if (firstDay === 0) {
startDiff = 1;
} else if (firstDay === 1) { // 第一天是周一
startDiff = 0;
} else {
startDiff = 7 - firstDay + 1;
}
return parseInt(Math.ceil((todayYear - startDiff) / 7)); // 返回今天是今年第几周
};
let index = new Date('1/3/2022').toLocaleDateString().weekIndexInYear()
console.log('今年第几周',index);
</script>
</body>
</html>
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交