How to output the saved date from JSON in mat-date-picker?

625 Views Asked by At

I want to output from the JSON the date in the input field of the mat-datepicker. When I run the output I always get the current year. I am working with ReactiveForms. What am I doing wrong?

My code:

// JSON

{
    "success": true,
    "mandant": {
        "mandantId": 2,
        "firm": "Test GmbH",
        "street": "Test-Street",
        "number": "2",
        "zip": "5xxxx",
        "city": "Exxxxxxxx",
        "country": "Germany",
        "financial_year_start": "Jan. 1, 2020" // This is to be output in the input
    }
}
// TS

public getFiscalYearStart: string;

  ngOnInit() {
    // To initialize forms
    this.initForm();

    // To initialize loadFinancialYearStart
    this.loadFinancialYearStart();
  }

// Creation of the settingsContentForm
  private initForm() {
    // General
    this.settingsContentForm = this.formBuilder.group({
      financial_year_start: new FormControl(moment(this.getFiscalYearStart), Validators.required),
    });
  }

  /**
   * Fill the datePicker with data
   */
  loadFinancialYearStart() {
    this.userAreaService.getCurrentMandantData().subscribe(resp => {
      this.getFiscalYearStart = resp.mandant.financial_year_start;
      console.log(this.getFiscalYearStart); // Correct year is displayed in the console
    });
  }
2

There are 2 best solutions below

0
On

Do it in two steps 1) parse the string into a Date Object with the date parse function, 2) then set it to your Date Picker

To parse the string into a date format use the Date.parse() helper from MDN with a date format example of what your JSON string will send.

Just to be sure, I would check if its in value, or in the object

//Step 1  financial_year_start.value

const unixTimeZero = Date.parse(financial_year_start.value);
// is it in the value Object
const financial_year_startDateValueAttribute = Date.parse(financial_year_start.value);
const financial_year_startDate = Date.parse(financial_year_start);

console.log(unixTimeZero);
// expected output: 0

console.log(financial_year_startDate );

// look if its in the value
console.log(financial_year_startDateValueAttribute );

// Now you have a date object you can set to Mat date picker

You can also do it with the date constructor, but first convert that String date into a Date object using the Date constructor:

  var date = new Date(financial_year_start.value);
0
On

This might be related to Date format issue and DatePicker is showing current date because it's not able process the date string.

Give it a try and make below changes in JSON

"financial_year_start": new Date("2020/01/01").toDateString()