Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change format of md-datepicker in Angular Material with momentjs

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?

like image 733
dearn44 Avatar asked Sep 14 '15 13:09

dearn44


People also ask

How can I change the format of MAT-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' } };

How do I change the date format on a Maryland datepicker?

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.

How can use datepicker in angular materials?

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.


2 Answers

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.

like image 174
Bohuslav Burghardt Avatar answered Oct 23 '22 13:10

Bohuslav Burghardt


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

like image 62
shulito Avatar answered Oct 23 '22 11:10

shulito