代码之家  ›  专栏  ›  技术社区  ›  GoGo

使用ngx日期选取器更改[(ngmodel)]上的日期格式

  •  0
  • GoGo  · 技术社区  · 6 年前

    我有一个记录出生日期的网络表单。我用 ngx-bootstrap 版本:2.0.2日期选取器模块。 我有一个API,它只接受日期值 MM-dd-yyyy 格式。我的挑战是确定这个日期值,以便将其发送到API。

    以下是我迄今为止所做的尝试:

    使用 bsConfig 如下:

      ngOnInit() {
        this.bsConfig = {
          containerClass: 'theme-red',
          dateInputFormat: 'MM-dd-yyyy'
        };
    }
    

    下面是我的HTML输入:

    <input class="form-control" 
            type="text" bsDatepicker 
            [bsConfig]="bsConfig" 
            placeholder="Date of Birth" 
            [(bsValue)]="participant.dob" value="{{ participant.dob | date:'yyyy-MM-dd' }}"
            name="dob" 
            [(ngModel)]="participant.dob" 
            #dob="ngModel">
    

    当我从日期选择器中选择日期时,我将日期视为我在ngoninit中设置的格式。但是,实际日期值为 { "dob": "2018-06-07T16:53:52.000Z" } .这是我发送到API的日期。因此,它不起作用。如上所述,我需要发送到API的日期格式必须是 年月日 格式。

    我如何塑造这个捕获的日期格式,以便将这个值发送到我的API?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Jun Kang    6 年前

    在将日期发送到API之前,请使用 formatDate() .

    别忘了导入它: import { formatDate } from '@angular/common';

    constructor(@Inject(LOCALE_ID) private locale: string) {}
    myDate;
    bsConfig;
    
    ngOnInit() {
      this.bsConfig = {
        containerClass: 'theme-red',
        dateInputFormat: 'MM-dd-yyyy'
      };
    }
    
    sendDataToApi() {
      const date = formatDate(this.myDate, this.bsConfig.dateInputFormat, this.locale);
      howeverImSendingDataToApi(whateverData, date);
    }