Search code examples
angulardatepickerbootstrap-datepickerngx-bootstrapdate-pipe

Angular 4 ngx-bootstrap datepicker-how to transform DATE-FORMAT from DD-MM-YYYY to YYYY-MM-DD while clicks on Submit


Here i am using ngx-bootstrap datepicker with DatePipe

how to transform DATE-FORMAT from DD-MM-YYYY to YYYY-MM-DD while clicks on Submit

*My Template - component.html

 <input type="text"
                   placeholder="FromDate"
                   class="form-control"
                   placement="top"
                   formControlName="fromDate"  [bsConfig]="{ dateInputFormat: 'DD-MM-YYYY' }"
                   bsDatepicker style="padding: 16px">

component.ts

ngOnInit() {
    this.LicenseDistributionForm.controls['toDate'].setValue(this._datePipe.transform(this.today, 'dd-MM-yyyy'));

this.LicenseDistributionForm.controls['fromDate'].setValue(this._datePipe.transform(this.firstDay, 'dd-MM-yyyy'));
    }

    submit() {
    if (!this.LicenseDistributionForm.valid) {
      this.validateAllFormFields(this.LicenseDistributionForm);
      console.log('Not valid!');
      return;
    }
    const params: any = {};

    params.fromDate = this.LicenseDistributionForm.value.fromDate;
    params.toDate = this.LicenseDistributionForm.value.toDate;


    {

    console.log('params', params);
         }
    this.organizationService.getLicenseDistributionSPDate( params.fromDate, params.toDate )
      .subscribe(licensedistributions => {
        this.licensedistributions = licensedistributions;
        console.log(licensedistributions, 'licensedistributions');
        // this.licensedistributionLoader=true;
      });

Solution

  • Using momentjs

    moment(dateDDMMYYYY, 'DD-MM-YYYY').format('YYYY-MM-DD');
    

    You can also apply more validation to that statement.

    var momentObj = moment(dateDDMMYYYY, 'DD-MM-YYYY', true);
    
    if ( !momentObj.isValid() ) throw "Invalid date";
    
    dateYYYYMMDD = momentObj.format('YYYY-MM-DD');