解决前后端日期传输因时区差异导致日期少一天的问题
前端处理
1. 发送日期字符串而非时间戳
在前端使用日期选择器(如 el-date-picker
)获取日期后,将日期转换为特定格式的字符串(如 YYYY-MM-DD
)发送给后端,避免直接发送带有时区信息的时间戳或日期对象。这样做的好处是将日期信息以一种通用、无歧义的格式传递,减少后端处理时区的复杂性。
vue
<template>
<el-form :model="warehousingForm" ref="formRef">
<el-form-item label="生产日期" prop="productionDate">
<el-date-picker v-model="warehousingForm.productionDate" type="date" placeholder="选择日期">
</el-date-picker>
</el-form-item>
<el-form-item label="有效期" prop="expiringDate">
<el-date-picker v-model="warehousingForm.expiringDate" type="date" placeholder="选择日期">
</el-date-picker>
</el-form-item>
<el-button @click="submitForm">提交</el-button>
</el-form>
</template>
<script>
export default {
data() {
return {
warehousingForm: {
productionDate: null,
expiringDate: null
}
};
},
methods: {
submitForm() {
if (this.warehousingForm.productionDate) {
this.warehousingForm.productionDate = this.formatDate(this.warehousingForm.productionDate);
}
if (this.warehousingForm.expiringDate) {
this.warehousingForm.expiringDate = this.formatDate(this.warehousingForm.expiringDate);
}
// 模拟发送请求
console.log(JSON.stringify(this.warehousingForm));
},
formatDate(date) {
const d = new Date(date);
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
}
};
</script>