如何在NestJs中将yyyy-MM-dd格式日期转换为dd-MM-yyyy格式
日期格式转换方案(yyyy-MM-dd → dd-MM-yyyy)
方法1:TypeORM实体自定义转换
直接在实体字段上配置转换器,数据库存储保持标准date格式,返回前端时自动转为dd-MM-yyyy:
import { Transform } from 'class-transformer'; import { IsOptional } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; import { Column } from 'typeorm'; // 日期转换函数 const formatDateToDDMMYYYY = (value: Date) => { if (!value) return null; const day = String(value.getDate()).padStart(2, '0'); const month = String(value.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需+1补正 const year = value.getFullYear(); return `${day}-${month}-${year}`; }; export class YourEntity { @IsOptional() @ApiProperty({ example: '1999-12-12', nullable: true }) @Column({ type: 'date', nullable: true }) @Transform(({ value }) => formatDateToDDMMYYYY(value), { toPlainOnly: true }) // 仅在返回前端时触发转换 birthDate?: Date; }
方法2:DTO层响应转换
如果不想修改实体结构,可以在返回数据的DTO中处理格式:
import { Expose, Transform } from 'class-transformer'; export class EntityResponseDto { @Expose() @Transform(({ obj }) => { if (!obj.birthDate) return null; const date = new Date(obj.birthDate); const day = String(date.getDate()).padStart(2, '0'); const month = String(date.getMonth() + 1).padStart(2, '0'); const year = date.getFullYear(); return `${day}-${month}-${year}`; }) birthDate?: string; }
在控制器中用plainToInstance(EntityResponseDto, entity)转换实体后返回即可。
方法3:Service层手动处理
在业务逻辑层直接转换后返回,适合临时场景:
async getEntityById(id: number) { const entity = await this.yourRepository.findOneBy({ id }); if (entity?.birthDate) { const date = new Date(entity.birthDate); // 返回新对象避免修改实体类型 return { ...entity, birthDate: `${String(date.getDate()).padStart(2, '0')}-${String(date.getMonth() + 1).padStart(2, '0')}-${date.getFullYear()}` }; } return entity; }
注意事项
- 数据库date类型本身无格式,读取时默认转为yyyy-MM-dd字符串或Date对象,转换前要确保Date对象有效,避免出现
Invalid Date。 - 使用
padStart(2, '0')保证日、月为两位数字(如1号转为01,3月转为03)。
内容的提问来源于stack exchange,提问作者Nabeel_kashmiriii
相关产品推荐
相关产品推荐

