如何在TypeORM中正确获取带时区Timestamp?解决时区偏移问题
解决TypeORM查询带时区时间返回少一小时的问题
问题根源
数据库字段类型为timestamp with time zone,但TypeORM模型中误用了date类型。TypeORM的date类型会默认将数据库中的带时区时间转换为UTC时区的Date对象,导致返回结果比原时间少1小时(原时间是东一区+01,UTC比东一区晚1小时)。
具体解决方法
1. 修正TypeORM模型字段类型
将模型中对应字段的类型改为与数据库匹配的timestamp with time zone:
// 错误写法 @Column({ type: 'date' }) yourDateField: Date; // 正确写法 @Column({ type: 'timestamp with time zone' }) yourDateField: Date;
2. 配置TypeORM连接时区
在TypeORM的连接配置中添加时区参数,确保数据库连接时使用指定时区(或UTC):
// 连接配置示例(以PostgreSQL为例) const connectionOptions: ConnectionOptions = { type: 'postgres', host: 'localhost', port: 5432, username: 'your_username', password: 'your_password', database: 'your_db', entities: [__dirname + '/**/*.entity{.ts,.js}'], synchronize: true, timezone: '+01:00' // 可设置为东一区,或保持'UTC'由前端处理时区转换 };
3. 手动转换时区(应急方案)
如果无法修改模型或连接配置,可在查询后手动将UTC时间转换为目标时区:
// 假设查询结果中的时间为utcDate const utcDate = new Date('2022-11-22T23:08:00.000Z'); // 转换为东一区时间 const targetDate = new Date(utcDate.getTime() + 3600 * 1000); // 或使用Intl API格式化 const formattedDate = new Intl.DateTimeFormat('zh-CN', { timeZone: 'Europe/Paris', // 东一区对应的时区标识符 year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).format(utcDate);
内容的提问来源于stack exchange,提问作者AlejandroOO
相关产品推荐
相关产品推荐

