时区异常

https://juejin.cn/post/7273119689185198117

@CreateDateColumn()自动生成时间,发现相差8小时

原因: 时区不一致

解决方法:

确认node环境时间正常,终端直接输入date命令查看确认服务器时间正常确认mysql数据库时间正常,workbench使用 select now(); 命令查看,如果不一致, 执行 set global time_zone = '+8:00'; 再执行 flush privileges;

所有时间都正常了,但是返回前端的结果和数据库存储的还是差8小时

原因是typeorm要进行timezone设置,设置 timezone: "+08:00", 或者 timezone: "Z"


import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn } from 'typeorm';

// ormconfig.ts

imports: [
        TypeOrmModule.forRootAsync({  
            imports: [ConfigModule],
            inject: [ConfigService],
            useFactory: (configService: ConfigService) =>({
              type: 'mysql',
              host: configService.get('DBHOST'),
              port: 3306,
              username: 'root',
              password: configService.get('DBPWD'),
              database: 'xzz222',
              entities: allEntities,
              synchronize: true,  // 同步本地的schema与数据库
              timezone: "Z", // 纠正时区偏差8小时  <<<<<<<<<------------------------
              logging: ['error'],  //日志记录类型  数据库操作记录
            } as TypeOrmModuleOptions ),
          }),
    ]