According to the docs a Date object should be converted to a string:
Note, that dates will be converted to strings when you'll try to convert class object to plain object.
My example-code with class-transformer 0.2.3 does not work as expected:
class TestDate {
@Type(() => Date)
aDate!: Date;
}
const testDate = new TestDate();
testDate.aDate = new Date();
const result: any = classToPlain(testDate);
console.log(typeof result.aDate);
This prints object to the console, but I'd expect string.
What am I missing?
To expand on TmTron's answer, I needed to create two transformers - one in each direction. I then combined them into one decorator using this technique:
// TransformDate.ts
import { Transform } from "class-transformer";
export default function TransformDate() {
const toPlain = Transform((value) => (value as Date).toISOString(), {
toPlainOnly: true,
});
const toClass = Transform((value) => new Date(value), {
toClassOnly: true,
});
return function (target: any, key: string) {
toPlain(target, key);
toClass(target, key);
};
}
Usage:
// User.ts
import TransformDate from './TransformDate';
export default class User {
id: string;
@TransformDate()
createdDate: Date;
// ...
}
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