Angular material introduced a new date picker component found here.
I want the date returned by this component to be in the format yyy-mm-dd but I am not sure how is this done. By searching I found that $mdDateLocaleProvider
can be used, but I could not find an example of using it.
Can someone show me a working example of formatting the date returned by md-datepicker
?
How to change Mat-Datepicker date format to DD/MM/YYYY in simplest way? First, bind the format to your mat-datepicker. export const MY_FORMATS = { parse: { dateInput: 'LL' }, display: { dateInput: 'YYYY-MM-DD', monthYearLabel: 'YYYY', dateA11yLabel: 'LL', monthYearA11yLabel: 'YYYY' } };
formatDate = function(date) { return moment(date). format('YYYY-MM-DD'); }; }); If you don't use moment. js, substitute the code inside formatDate for whatever you wish to use to format the date.
mat-datepicker exampleAdd a template reference variable mat-datepicker element. Connect mat-datepicker to input element via [matDatepicker] property. Finally add date picker toggle button to display or hide calender popup by using mat-datepicker-toggle element.
There is a documentation for $mdDateLocaleProvider
in the Angular Material docs.
angular.module('app').config(function($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('YYYY-MM-DD');
};
});
If you don't use moment.js, substitute the code inside formatDate
for whatever you wish to use to format the date.
Here is a CodePen example based on the samples from Angular Material docs.
To also address the problem pointed out by kazuar:
Unfortunately it doesn't work if the date is typed from the keyboard
you should define the parseDate method as well. From the docs:
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'L', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
For a full example, I have in my app (using moment):
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('DD/MM/YYYY');
};
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'DD/MM/YYYY', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
Regards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With