JavaScript 关于 JSON.stringify() 导致的 Date 时区问题
先说结论。
解决方案
在调用 stringify 之前把 Date 类型先格式化为字符串避免。
serializer.js
export default {
/**
* 解决 stringify 导致的时区丢失,提前把所有日期类型字段转化为字符串
* @param data 转换对象
* @returns {*}
*/
formatDateTime(data){
for (const key in data){
const value = data[key]
if (value instanceof Date) {
const year = value.getFullYear()
const month = (value.getMonth() < 9 ? '0' : '') + (value.getMonth() + 1)
const day = (value.getDate() < 10 ? '0' : '') + value.getDate()
const hour = (value.getHours() < 10 ? '0' : '') + value.getHours()
const minute = (value.getMinutes() < 10 ? '0' : '') + value.getMinutes()
const second = (value.getSeconds() < 10 ? '0' : '') + value.getSeconds()
const milliseconds = (value.getSeconds() < 100 ? value.getSeconds() < 10 ? '00' : '0' : '') + value.getSeconds()
data[key] = `${year}-${month}-${day}T${hour}:${minute}:${second}.${milliseconds}Z`
}
}
return data
}
}
2025年4月9日大约 1 分钟