NestJS: How to convert Date object to custom format (custom string or unix timestamp)

Viewed 9921

I'm building a NestJS API and I would like to expose to the API my Date objects as unix timestamps / custom string formats.

By default, NestJS use the format shown in this example: "2020-02-24T07:01:31.229Z"

Any idea of how to easily configure this without having to make my API objects hold a "number" or "string" (aka, manually converting it) instead of a Date?

Note that I'm not asking about TypeORM and how to store date objects. This is a question about how to make the NestJS serialize/deserialize Date objects into JSON.

Thanks,

2 Answers

If you want to change some of the classes:

From 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;
}

For my case, I want all dates to be transformed. I did not find a proper way to do it but I managed to change the date format globally.

In my main.ts I have added:

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

As of 8 Dec 2020 (v7.6.0) this is now possible.

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

then use the Logger Class

app.useLogger(app.get(MyLogger))

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

Related