4

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,

1
  • Are you using ClassTransformer (or the ValidationPipe with transform: true)? Commented Feb 24, 2020 at 12:31

2 Answers 2

3

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();
};
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.