0

I want to change the date format from dd/mm/yyyy to dd-mm-yyyy please look at the reference image once for clarity:

Reference image

HTML

<div fxFlex="calc(25% - 30px)">
  <mat-form-field appearance="outline" class="w-100">
    <mat-label>Date of birth</mat-label>
    <input matInput type="date" [formControlName]="'dateOfBirth'" placeholder="Select entry date" required>
    <mat-error *ngIf="dateFormat">
      <strong>Kindly enter a valid date</strong>
    </mat-error>
  </mat-form-field>
</div>

TS

dateFormat: boolean;

validateDate() {
  if (this.memberForm.get('dateOfBirth').value == '') {
    this.dateFormat = true;
  }
}

ngOnInit() {
  this.validateDate();
}
JSON Derulo
  • 9,780
  • 7
  • 39
  • 56
Revanth Reddy
  • 15
  • 1
  • 6
  • You are using [input type="date"](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date) which has some limitations. It's stated there that "the displayed date is formatted based on the locale of the user's browser" And there seems to be no way to customize it, so I guess you can't use the browser's native datepicker with that requirements. However, the `value` behind has always the same format. – JSON Derulo Nov 08 '21 at 11:17
  • means cant we change that default date format which was created by angular people? – Revanth Reddy Nov 08 '21 at 11:21
  • This has nothing to do with Angular. As I said, you are using the browser's native date input field, which has the limitations I mentioned. Either you live with it, or you need to use a completely different component, e.g. [Angular Material's Datepicker](https://material.angular.io/components/datepicker/overview) – JSON Derulo Nov 08 '21 at 11:29
  • Does this answer your question? [Is there any way to change input type="date" format?](https://stackoverflow.com/questions/7372038/is-there-any-way-to-change-input-type-date-format) – JSON Derulo Nov 08 '21 at 11:53

1 Answers1

0
import { DatePipe } from '@angular/common'
...
constructor(public datepipe: DatePipe){}
...
myFunction(){
this.date=new Date();
let latest_date =this.datepipe.transform(this.date, 'yyyy-MM-dd');
}

and just add Datepipe in 'providers' array of app.module.ts. Like this:

import { DatePipe } from '@angular/common'
...
providers: [DatePipe]