【问题标题】:How to show the correct date in format of datepicker in Angular material如何在 Angular 材料中以 datepicker 的格式显示正确的日期
【发布时间】:2019-10-07 11:08:22
【问题描述】:

我有一个 Angular 8 应用程序。我正在使用材料的日期选择器。

但是如果我填写一个日期调用 get api 调用:

  searchFor(filterRegistration: FilterByRegistrationDTO) {
    // tslint:disable-next-line: max-line-length
    console.log(
      this.participantService.filterParticipantsByRegistration(1, "Invited", this.startDate.toString()).subscribe(result => {       
        console.log(this.startDate.toString());
        console.log(result);
      })
    );

模板看起来像这样:

    <div>
      <mat-form-field  class="search-field-input">
        <input matInput [matDatepicker]="picker1" placeholder="start datum" [(ngModel)]="startDate"  />
        <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
        <mat-datepicker #picker1></mat-datepicker>
      </mat-form-field>
    </div>

所以在服务器端日期将显示为:jjjj-MM-dd。

但在客户端,日期必须显示为:dd-MM-jjjj。

但是如果我调用 api 调用:

console.log(
      this.participantService.filterParticipantsByRegistration(1, "Invited", this.startDate.toString()).subscribe(result => {
        console.log(this.startDate.toString());
        console.log(result);
      })
    );

然后我会得到这个错误:

core.js:12584 ERROR 
HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "https://dev-engine.mijnhep.nl/api/medical/organisa…GMT%2B0200%20(Central%20European%20Summer%20Time)", ok: false, …}
error:
Start: ["The value 'Mon Oct 07 2019 12:58:46 GMT+0200 (Central European Summer Time)' is not valid for Start."]
__proto__: Object
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for https://dev-/api/medical/organisation/1/Participant/filter-by-registration?Filter=Invited&Start=Mon%20Oct%2007%202019%2012:58:46%20GMT%2B0200%20(Central%20European%20Summer%20Time): 400 Bad Request"
name: "HttpErrorResponse"
ok: false
status: 400
statusText: "Bad Request"
url: "/api/medical/organisation/1/Participant/filter-by-registration?Filter=Invited&Start=Mon%20Oct%2007%202019%2012:58:46%20GMT%2B0200%20(Central%20European%20Summer%20Time)"
__proto__: HttpResponseBase

所以我的问题是。如何在客户端填写正确的日期格式。这样就不会报错了?

谢谢

【问题讨论】:

  • 您可以使用 javascript 来解析格式或使用像 moment.js 或日期函数这样的库来轻松地为您包装它。
  • 谢谢。但是一个例子会很好
  • 为什么不格式化提交的日期??而不是 this.startDate.toString() 正确格式化日期?
  • 是的,好的。但是格式??你能举个例子吗?会很好

标签: javascript angular datepicker angular-material


【解决方案1】:

您可以使用 JSON.stringify(yourDate) 使用 iso 日期格式

然后在服务器端使用这个值。

否则,在客户端,您可以使用moment(yourDate).format('L');

https://momentjs.com/

在您的代码中,它将是:

this.participantService.filterParticipantsByRegistration(1, "Invited", JSON.stringify(this.startDate))

this.participantService.filterParticipantsByRegistration(1, "Invited", moment(yourDate).format('L'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 2021-03-26
    • 1970-01-01
    相关资源
    最近更新 更多