【问题标题】:How to convert Angular locale date to proper date format for API to consume?如何将 Angular 语言环境日期转换为 API 使用的正确日期格式?
【发布时间】:2019-05-31 07:16:10
【问题描述】:

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

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 date querystringparameter date-pipe


    【解决方案1】:

    您始终可以将 Angular 的 DatePipeFormatDate 导入到您的 component.ts 中,并将 searchLeaveApplication.startDate 转换为 .Net 核心接受的所需日期时间格式。可以在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
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多