angular material datapicker different format after submit a form

∥☆過路亽.° 提交于 2019-12-12 22:48:11

问题


When I select a data it fills the input with a format like

DD/MM/YYYY

but I need to send that data through a form, when I do a console.log on my component

datapicker.component.ts

onFindAWhip(form: NgForm){
    const value = form.value;
    console.log(value);
 }

I'm getting a full date like

Thu Sep 28 2017 00:00:00 GMT+0100 (GMT Daylight Time)

do I have to reformat again ?

it's already done in my DateAdapter, I've tried to get it from here but I just get errors

import { NativeDateAdapter }  from '@angular/material';

export class MyDateAdapter extends NativeDateAdapter {
   format(date: Date, displayFormat: Object): string {

      let day = date.getDate();
      let month = date.getMonth();
      let year = date.getFullYear();

      if (displayFormat == "input") {


          let pickupData = date.toDateString();
          let pickupDataArray = pickupData.split(" ");
          let yearPicked = pickupDataArray[3]; 

          const without = pickupData.substring(0, pickupData.length-4);

          return without + '     '+yearPicked ;

       } else if (displayFormat == "input-home") {
          return this._to2digit(day) + '/' + this._to2digit(month) +'/'+ year;
       }

       else{
        return date.toDateString();
      }
   }

   private _to2digit(n: number) {
       return ('00' + n).slice(-2);
   }

}

datapicker.html

<span class="calendar-to">
        <button md-raised-button (click)="pickupTo.open()" class="search--icon"></button>
        <input  [mdDatepicker]="pickupTo"
                placeholder="DD/MM/YYYY"
                name="date_to"
                ngModel>
        <md-datepicker touchUi="true" #pickupTo></md-datepicker>
    </span>

回答1:


This is because the ngModel is a DateTime, and includes all that information. You will have to process it inside your component.ts if you only want DD/MM/YYYY. You can actually just use Angular's DatePipe inside your component to quickly and easily do this for you.

import the pipe:

import { DatePipe } from '@angular/common'

build access:

constructor( private datePipe: DatePipe ) { }

use in method:

onFindAWhip(form: NgForm){
    const value = form.value;
    console.log(this.datePipe.transform(value, 'MM/dd/y'));
 }


来源:https://stackoverflow.com/questions/46118812/angular-material-datapicker-different-format-after-submit-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!