Change format of md-datepicker in Angular Material with momentjs Change format of md-datepicker in Angular Material with momentjs angularjs angularjs

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;  };});