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,
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();
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With