5
votes

I'm using https://material.angular.io/components/component/datepicker in my angular4 project. How can I format selected date in input box with short format like "May 29, 2017". Currently it is displayed as 29/05/2017

Sample code:

<md-input-container>
  <input mdInput readonly="true" [mdDatepicker]="startDatePicker" [mdDatepickerFilter]="myFilter" [min]="minDate" [max]="maxDate" class="date-text ng-dirty ng-valid-parse ng-touched ng-not-empty ng-valid ng-valid-required" placeholder="Choose a date">
  <button mdSuffix [mdDatepickerToggle]="startDatePicker" class="date-icon"></button>
</md-input-container>

<md-datepicker #startDatePicker [dateFormat]="'LL'" startView="month" [startAt]="currentDate"></md-datepicker>

TS:

@ViewChild('startDatePicker') startDatePicker: MdDatepicker<Date>;

PS. [dateFormat]="'LL'" is not working

2
Please post the code you have. There is a section at the link you posted for date formatting. - Simon Visser
updated :) thank you - d123546
Can you please post solution? - Igor Janković
I haven't found any solutions yet. :( - d123546

2 Answers

4
votes

You cannot set date format at the moment easily. There is no such property in Material 2 Datepicker API and the only proper way to change the format is to provide your own DateAdapter implementation. The official documentation doesn't provide any instructions about that. There is only one basic implementetion right now which defines formats according to the locale. There are many complains about that and more adapters should come soon. You can try to use one based on moment.js from this issue-thread or just wait.

You can also play with locales to get different formats in your Datepicker. But it's just a workaround till a proper official solution comes:

export class AppModule {
  constructor(private dateAdapter:DateAdapter<Date>) {
    dateAdapter.setLocale('de'); // DD.MM.YYYY
  }
}
0
votes

I'd rather use module providers for that:

@NgModule({
...
providers: [
     { provide: LOCALE_ID, useValue: navigator.language }
     ...
  ]
})
export class AppModule { }

or you can replace navigator.language by 'de' to achieve the same as above.