这是来自一位dayjs访客提的问题,正好有点时间就写了一个解决方案供参考
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>dayjs获取年周数及周时间范围</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.0/vue.min.js"></script>
<script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>
<script src="https://unpkg.com/dayjs@1.8.21/plugin/weekOfYear.js"></script>
<script src="https://unpkg.com/dayjs@1.8.21/plugin/isoWeeksInYear.js"></script>
<script src="https://unpkg.com/dayjs@1.8.21/plugin/isLeapYear.js"></script>
<style>
select {
padding: 6px 10px;
}
table {
margin-top: 10px;
}
th,td {
padding: 6px 10px;
white-space: nowrap;
}
</style>
</head>
<body>
<div id="js_app">
<select v-model="year">
<option v-for="v in years" :value="v">{{ v }}</option>
</select>
<table border="1" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th v-for="v in weeks" :key="v">第{{ v }}周</th>
</tr>
</thead>
<tbody>
<tr>
<td v-for="item in weeksTimeRang">
开始时间:{{ item.startTime }}<br>
结束时间:{{ item.endTime }}
</td>
</tr>
</tbody>
</table>
</div>
<script>
dayjs.extend(window.dayjs_plugin_weekOfYear)
dayjs.extend(window.dayjs_plugin_isoWeeksInYear)
dayjs.extend(window.dayjs_plugin_isLeapYear)
var app = new Vue({
el: '#js_app',
data() {
return {
year: '2019',
years: ['2019', '2020', '2021', '2022'],
weeks: 0,
weeksTimeRang: []
}
},
watch: {
year() {
this.assignWeeks();
}
},
methods: {
assignWeeks() {
this.weeks = dayjs(this.year).isoWeeksInYear();
let weeksTimeRang = [];
for(let i=1; i<=this.weeks; i++) {
weeksTimeRang.push({
startTime: dayjs(this.year).week(i).startOf('week').format('YYYY-MM-DD'),
endTime: dayjs(this.year).week(i).endOf('week').format('YYYY-MM-DD')
})
}
this.weeksTimeRang = weeksTimeRang;
}
},
mounted() {
this.assignWeeks();
}
});
</script>
</body>
</html>