sandeep v
sandeep v

Reputation: 43

how to set the date format in mat date picker in angular

I had a form that consists of a form-control as date picker with a mat date picker. when I select the date using the date picket the form control is taking a date class. I need to convert it into string. Kindly help me in this html code:

<mat-form-field appearance="fill">
                <input matInput [matDatepicker]="picker" formControlName="date" placeholder="Choose a date">
                <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                <mat-datepicker #picker></mat-datepicker>
            </mat-form-field>

When I am select a date it should convert into as 11-05-2020(dd-mm-yyyy) for the form control on submit. Kindly help me

Edit:

 import { Component, OnInit } from '@angular/core';
    import { ProductsService } from '../products/products.service';
    import { forkJoin } from 'rxjs';
    import { FormControl, Validators, FormBuilder, FormArray } from '@angular/forms';
    import { Router } from '@angular/router';
    import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';

    @Component({
      selector: 'app-orders',
      templateUrl: './orders.component.html',
      styleUrls: ['./orders.component.scss'],
      providers: [ProductsService, {provide: MAT_DATE_LOCALE, useValue: 'en-GB'}]
    })
    export class OrdersComponent implements OnInit {
       paginationPageSize:any;
       getRowHeight:any;
    statusList=['open','closed'];
    form = this.fb.group({

      city: new FormControl('', Validators.required),
      date: new FormControl('', Validators.required),
      status: new FormControl('', Validators.required),
      pageNum:0,
      pageSize:10,
      preOrders: new FormControl(false, Validators.required),
     });
     constructor(private productsService: ProductsService, private fb: FormBuilder, private router: Router) { }

      ngOnInit() {
      }

      onSubmit() {
        if (this.form.valid) {
          const value = this.form.value;
        }
    }


    }

I have added in the provider but still it is not working.

Upvotes: 0

Views: 2573

Answers (1)

T. Sunil Rao
T. Sunil Rao

Reputation: 1257

You can change date format using Internationalization Locale

Set Locale in your component TS...

@Component({
  selector: ...,
  templateUrl: ...,
  styleUrls: ...,
  providers: [
    {provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
  ],
  ...
})
export class Component ...

If you want to change it globally, set Locale in your app.module.ts

@NgModule({
  providers: [
    {provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
  ],
})
export class AppModule {}

Reference: https://material.angular.io/components/datepicker/overview#internationalization

Hope it helps!

Upvotes: 1

Related Questions