得到当前一周日期,以及对应的星期几

273 阅读1分钟

上代码

<template name="calendar">
	<view class="container">
		<view class="week">
			<ul v-for="i in week">
				<li>{{ i.label }}</li>
			</ul>
		</view>
		<view class="day">
			<ul v-for="i in days">
				<li v-bind:class="[i.day == today1 ? 'activeClass' : '']">{{ i.day }}</li>
			</ul>
		</view>
	</view>
</template>

<script>
export default {
	name: 'calendar',
	props: {
		today: ''
	},
	data() {
		return {
			week: [
				{
					label: '日',
					val: '0'
				},
				{
					label: '一',
					val: '1'
				},
				{
					label: '二',
					val: '2'
				},
				{
					label: '三',
					val: '3'
				},
				{
					label: '四',
					val: '4'
				},
				{
					label: '五',
					val: '5'
				},
				{
					label: '六',
					val: '6'
				}
			],
			days: this.getThisWeek(),
			today1: new Date().getDate()
		};
	},
	methods: {
		/* 获取当前一周日期 */
		getThisWeek() {
			let arr = []; /* 搞一个数组接受当前周几、几号的数组 */
			let date = new Date(); /* 获得当前日期 */
			let days = new Date(date.getYear(), date.getMonth() + 1, 0).getDate(); /* 获得这个月有多少天 */
			let preDays = new Date(date.getYear(), date.getMonth(), 0).getDate(); /* 获得上个月有多少天 */
			let day = new Date().getDate(); //得到当前几号
			let index = new Date().getDay(); //得到周几
			/* 日期往左 */
			for (let i = index, tempDay = day; i >= 0; i--) {
				if (tempDay < 1) {
					tempDay = preDays;
					arr.push({ day: tempDay, index: i });
					tempDay--;
					continue;
				}
				arr.push({ day: tempDay, index: i });
				tempDay--;
			}
			arr.reverse(); /* 翻转数组 */

			/* 日期往右 */
			for (let i = index + 1, tempDay = day + 1; i <= 6; i++) {
				if (tempDay > days) {
					tempDay = 1;
					arr.push({ day: tempDay, index: i });
					tempDay++;
					continue;
				}
				arr.push({ day: tempDay, index: i });
				tempDay++;
			}
			return arr;
		}
	},
	created() {
		this.getThisWeek();
	},
	mounted() {}
};
</script>

<style>
.container {
	width: 100%;
	height: 100rpx;
	border-bottom-left-radius: 20rpx;
	border-bottom-right-radius: 20rpx;
	background-color: rgb(0, 122, 255);
}
.week,
.day {
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
}
ul {
	display: flex;
	padding: 0;
	width: 14.28%;
	flex-direction: row;
	justify-content: center;
	align-items: center;
}
ul > li {
	width: 100%;
	height: 40rpx;
	list-style: none;
	text-align: center;
	line-height: 40rpx;
	margin: 0 auto;
	color: #ffffff;
	opacity: 0.5;
	font-size: small;
}
.activeClass {
	width: 50%;
	background-color: #ffffff;
	border-radius: 60rpx;
	color: rgb(0, 122, 255);
}
</style>

实现效果

今日日期对比