Change format of md-datepicker in Angular Material with momentjs
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
For those not using Moment.js, you can format as a string:
.config(function($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
return day + '/' + (monthIndex + 1) + '/' + year;
};
});
Worked perfectly when the date is typed from the keyborard and returned null in initiation to avoid the massage 'Invalid date' in md-datapicker directive:
$mdDateLocaleProvider.formatDate = function(date) {
return date ? moment(date).format('DD/MM/YYYY') : null;
};
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'DD/MM/YYYY', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};