如何在 mat-date-picker 中从 JSON 输出保存的日期?

问题描述

我想从 JSON 输出 mat-datepicker 输入字段中的日期。当我运行输出时,我总是得到当前年份。我正在使用 ReactiveForms。我做错了什么?

我的代码

// 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
    });
  }

解决方法

这可能与日期格式问题有关,DatePicker 显示当前日期,因为它无法处理日期字符串

试试看,并在 JSON 中进行以下更改

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

分两步完成 1) 使用 date parse function,Date Object) 将字符串解析为 2,然后将其设置为您的日期选择器

要将字符串解析为日期格式,请使用 Date.parse() helper from MDN 和您的 JSON 字符串将发送的日期格式示例。

为了确定,我会检查它是在值中还是在对象中

//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

您也可以使用日期构造函数来完成,但首先使用日期构造函数将该字符串日期转换为日期对象:

  var date = new Date(financial_year_start.value);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...