简体   繁体   中英

Convert date format in TypeScript

I am trying to filter a table based on year and month.

I want my date to have year and month only and i want the default date in my textbox as well, before doing the search.

When searching, I would patch the value into a textbox, while trying to convert my date with year and month to ISOString.

However I'm receving a null object for it when doing the following code:

this.Date = new Date();
this.Date.setMonth(this.Date.getMonth() - 10);

//init
this.form.get('Date').patchValue(this.Date);

//passing to isostring for api call
this.Date= new Date(this.form.get('Date').value).toISOString();


result
TypeError: Cannot convert undefined or null to object

What am i doing wrong?

One issue in the code could be that you are trying to patch the date value into the form control before it has been initialized. The patchValue method only works on an existing form control, and not on a null value.

To fix this issue, you can initialize the form control with the default date value before patching the new value, as follows:

this.Date = new Date();
this.Date.setMonth(this.Date.getMonth() - 10);

//init form control with default date value
this.form.get('Date').patchValue(this.Date);

//patch new value into form control
this.form.get('Date').patchValue(new Date());

//passing to isostring for API call
this.Date= new Date(this.form.get('Date').value).toISOString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM