TypeOrm中设置时区为上海

Published on
55

在 MySQL 中执行以下命令:

-- 设置全局时区
SET GLOBAL time_zone = '+8:00';
-- 设置当前会话时区
SET time_zone = '+8:00';
-- 刷新权限
FLUSH PRIVILEGES;

然后在你的 TypeORM 配置中(通常在 app.module.ts):

TypeOrmModule.forRoot({
  type: 'mysql',
  // ... 其他配置 ...
  timezone: '+08:00',        // 设置时区偏移
  dateStrings: true,         // 日期以字符串形式返回
  charset: 'utf8mb4',
})

实体配置保持简单:

// ... existing code ...

@Entity()
export class sysRole {
  // ... existing code ...

  @CreateDateColumn({
    comment: '创建时间',
    type: 'datetime',
    nullable: true,
  })
  create_time: Date;

  @UpdateDateColumn({
    comment: '更新时间',
    type: 'datetime',
    nullable: true,
  })
  update_time: Date;

  // ... existing code ...
}

这样设置后,所有的时间都会正确显示为北京时间。你可以通过以下 SQL 命令验证时区设置是否生效:

-- 查看当前时区设置
SHOW VARIABLES LIKE '%time_zone%';
-- 查看当前时间
SELECT NOW();

好了!


Prev Post Electron终端中文乱码解决方案
Next Post 记一次修改文件名称Git没有提交的问题