Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plainToClass does not convert a Date to string

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?

like image 442
TmTron Avatar asked Mar 14 '26 05:03

TmTron


1 Answers

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;
  // ...
}
like image 55
jjt Avatar answered Mar 17 '26 03:03

jjt



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!