微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?