【问题标题】:NestJS: How to convert Date object to custom format (custom string or unix timestamp)NestJS:如何将日期对象转换为自定义格式(自定义字符串或 unix 时间戳)
【发布时间】:2020-06-07 22:59:48
【问题描述】:

我正在构建一个 NestJS API,我想将我的 Date 对象作为 unix 时间戳/自定义字符串格式公开给 API。

默认情况下,NestJS 使用本例所示的格式:“2020-02-24T07:01:31.229Z

知道如何轻松配置它,而不必让我的 API 对象保存“数字”或“字符串”(也就是手动转换它)而不是日期吗?

请注意,我不是在询问 TypeORM 以及如何存储日期对象。这是一个关于如何让 NestJS 将 Date 对象序列化/反序列化为 JSON 的问题。

谢谢,

【问题讨论】:

  • 您使用的是ClassTransformer(或ValidationPipetransform: true)?

标签: typescript date date-format unix-timestamp nestjs


【解决方案1】:

自 2020 年 12 月 8 日 (v7.6.0) 起,这已成为可能。

@Injectable()
class MyLogger extends LoggerService {
    getTimestamp() {
        return new Date().toISOString()
    }
}

然后使用 Logger 类

app.useLogger(app.get(MyLogger))

https://github.com/nestjs/nest/pull/5681

【讨论】:

    【解决方案2】:

    如果你想改变一些类:

    来自https://github.com/typestack/class-transformer#basic-usage

    import { Transform } from "class-transformer";
    
    export class Model {
        @Type(() => Date)
        @Transform(value => value.valueOf(), { toPlainOnly: true })
        date: Date;
    }
    

    就我而言,我希望转换所有日期。我没有找到合适的方法,但我设法在全球范围内更改日期格式。

    在我的main.ts 中我添加了:

    Date.prototype.toJSON = function() {
        return this.valueOf();
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-23
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 2013-03-07
      • 2023-02-04
      相关资源
      最近更新 更多