如何将 Angular 语言环境日期转换为适合 API 使用的日期格式?

How to convert Angular locale date to proper date format for API to consume?

我在我的模板驱动表单中使用双向绑定:

ts:

searchLeaveApplication: any = {};

html:

<mat-form-field class="searchInputs">
  <input
    matInput
    [matDatepicker]="searchStartDate"
    [(ngModel)]="this.searchLeaveApplication.startDate"
    name="startDate"
  />
  <mat-datepicker-toggle
    matSuffix
    [for]="searchStartDate"
  ></mat-datepicker-toggle>
  <mat-datepicker #searchStartDate></mat-datepicker>
</mat-form-field>

但是我得到的是这个日期:

API(.Net 核心)的日期格式是不可接受的。如何将格式更改为正确的日期格式?我想我无法在双向绑定中使用日期管道。

您始终可以导入 Angular 的 DatePipe, or FormatDate into your component.ts, and convert searchLeaveApplication.startDate to the required datetime format that is accepted by .Net core. The full list of pre-defined options and custom formats can be found here

1) 如果您打算使用 DatePipe,您可以执行以下操作。

import { DatePipe } from '@angular/common';

export class SampleComponent implements OnInit {   

constructor(private datePipe: DatePipe) {}

  saveData() {
    const searchStartDateString = this.datePipe.transform(this.searchLeaveApplication.startDate, 'yyyy-MM-dd');
    // handle the rest
  }
}

不要忘记将 DatePipe 添加到模块中的提供程序。

providers: [DatePipe]

2) 或者,您可能想使用 formatDate:

import { formatDate } from '@angular/common';

export class SampleComponent implements OnInit {

  constructor(@Inject(LOCALE_ID) private locale: string) {}

  saveData() {
    const searchStartDateString = formatDate(this.searchLeaveApplication.startDate, 'MM-yyyy', this.locale);
    // handle the rest
  }
}