Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,

like image 572
vilanovi Avatar asked Oct 30 '25 04:10

vilanovi


1 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();
};
like image 154
i906 Avatar answered Nov 02 '25 00:11

i906



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!