我如何在 NestJs 中以这种格式"yyyy-MM-dd" "dd-MM-yyyy"转换日期格式



如何将日期格式转换为"dd-MM-yyyy"我得到的格式是"yyyy-MM-dd"下面是我的实体

中的代码
@IsOptional()
@ApiProperty({ example: '1999-12-12', nullable: true })
@Column({ type: 'date', nullable: true })
birthDate?: Date;

我想转换成这个格式"dd-MM-yyyy">

带有所需语言环境参数的toLocaleDateString将对您有所帮助。

transformDate(date: string): string {
const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
return new Date(date).toLocaleDateString('en-US', options);
}

试一试:

在任何你想要的服务中创建方法

transformDate(date: string): string {
const dateObject = new Date(date);
return dateObject.toLocaleDateString('en-GB', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
});
}

使用示例:

const date = '2022-12-28';
console.log(this.dateService.transformDate(date));

相关内容

最新更新