Angular获取错误时间戳:前后端日期不一致的配置方案咨询
解决前后端日期时区不一致问题
后端配置(主流框架示例)
Spring Boot(Java):在配置文件中指定时区,保证日期序列化和数据库交互时使用GMT+1:
spring.jackson.time-zone=GMT+1 spring.jpa.properties.hibernate.jdbc.time_zone=GMT+1配置后后端返回的日期会直接转换为GMT+1时区格式,前端将拿到
2022-11-15T08:45:00.000+01:00,与数据库存储值一致。Node.js(Express):借助日期处理库全局设置时区,或在响应序列化时指定:
// 使用moment设置默认时区 const moment = require('moment-timezone'); moment.tz.setDefault('GMT+1'); // 或在响应中直接转换 app.get('/data', (req, res) => { const dbDate = '2022-11-15 08:45:00'; const formattedDate = moment(dbDate).tz('GMT+1').format(); res.json({ date: formattedDate }); });
前端处理方案(后端无法修改时)
直接在前端将UTC时间转换为GMT+1时区的本地时间:
- 原生JavaScript:
const utcDate = new Date('2022-11-15T07:45:00.000+00:00'); const gmt1Date = utcDate.toLocaleString('de-DE', { timeZone: 'GMT+1', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }); // 输出:15.11.2022, 08:45:00 - Day.js工具:
import dayjs from 'dayjs'; import utc from 'dayjs/plugin/utc'; import timezone from 'dayjs/plugin/timezone'; dayjs.extend(utc); dayjs.extend(timezone); const formattedDate = dayjs('2022-11-15T07:45:00.000+00:00') .tz('GMT+1') .format('DD.MM.YYYY, HH:mm:ss');
数据库时区校验
确保数据库服务器时区设置为GMT+1,以MySQL为例:
SET GLOBAL time_zone = '+01:00'; SET SESSION time_zone = '+01:00';
内容的提问来源于stack exchange,提问作者serkancks
相关产品推荐
相关产品推荐

