解决方法 首先如果您发现日历上的日期比后台获取的日期大一天,那么可能是因为时区导致的问题。您可以尝试使用 moment.js 库来处理日期和时区的问题。
要引入 npm install moment-timezone
来安装 Moment.js 的时区功能
import moment from 'moment-timezone';
formatter(day) {
const formattedDate = moment(day.date).tz('Asia/Shanghai').format('YYYY-MM-DD');
const classItem = this.classList.find(
(item) => moment(item.classDate).format('YYYY-MM-DD') === formattedDate
);
if (classItem) {
if (classItem.classStatus === 1) {
day.bottomInfo = "已满";
day.selectable = false; // 已满的日期设置为不可选
} else if (classItem.classStatus === 2) {
day.bottomInfo = "停诊";
day.selectable = false; // 停诊的日期设置为不可选
} else {
day.bottomInfo = "可预约";
day.selectable = true; // 可预约的日期设置为可选
}
} else {
day.bottomInfo = "";
day.type = "disabled";
}
return day;
}
在上述代码中,我们使用 Moment.js 的 tz()
方法将日期转换为指定时区(在示例中是亚洲/上海时区)。这样,您应该能够确保获取的日期与您所期望的时区一致,并且日历上显示的日期正确对应后台的日期。
我的代码
<div class="medi2">
<van-field
readonly
clickable
name="calendar"
:value="value"
label="体检日期"
@click="showCalendar = true"
/>
<van-calendar
v-model="showCalendar"
@confirm="onConfirm"
:formatter="formatter"
title="选择体检日期"
:default-date="selectedDate"
></van-calendar>
</div>
这是我在data中定义的参数
showCalendar: false, // 控制日历组件的显示与隐藏
classList: [], // 从后端获取的班级列表
selectedDate: null, // 选中的日期
value: "请选择体检日期", // 格式化后的日期值
import moment from "moment-timezone"; 这个一定要
初始化
this.$nextTick(() => {
this.showCalendar = true;
});
fetchClassListFromBackend() {
// 日历
向接口发起请求 使用参数接受
},
下面的方法是最重要的 你的日历的日期和你从接口拿到的日期要进行匹配
formatter(day) {
const formattedDate = moment(day.date)
.tz("Asia/Shanghai")
.format("YYYY-MM-DD");
const classItem = this.classList.find(
(item) => moment(item.classDate).format("YYYY-MM-DD") === formattedDate
);
if (classItem) {
if (classItem.classStatus === 1) {
day.bottomInfo = "已满";
day.selectable = false; // 已满的日期设置为不可选
} else if (classItem.classStatus === 2) {
day.bottomInfo = "停诊";
day.selectable = false; // 停诊的日期设置为不可选
} else {
day.bottomInfo = "可预约";
day.selectable = true; // 可预约的日期设置为可选
}
} else {
day.bottomInfo = "";
day.type = "disabled";
}
return day;
},
下面的方法是选中后在页面展示的
onConfirm(date) {
this.selectedDate = date;
const formattedDate = `${date.getFullYear()}年${
date.getMonth() + 1
}月${date.getDate()}日`;
this.value = formattedDate;
this.showCalendar = false;
},