5

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

4
  • Please post the code you have. There is a section at the link you posted for date formatting. Commented May 29, 2017 at 8:43
  • updated :) thank you Commented May 29, 2017 at 8:48
  • Can you please post solution? Commented Jun 9, 2017 at 8:32
  • I haven't found any solutions yet. :( Commented Jun 9, 2017 at 9:29

2 Answers 2

4

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
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your answer. Ill try to play around this Adapter
Excuse me, where could we get the location id like "de"?
@Einsamer, do you mean a list of available locales?
Yes, it is. I think they should use switch-case somewhere
That works, but I tried to add it on the app module and it didn't work (I'm using a date picker in a sub-module)... That's annoying...
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.