Change format of md-datepicker in Angular Material with momentjs Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!AngularJS Material date picker date format not workingHow to format date in angularjsmd-datepicker input formati want set format of md-datepicker to dd-mm-yyyyChange md-datepicker ng-model formatFormat date in Angular JS material using model possible?How do I format Angular Material's md-datepicker for Django REST Framework?AngularJS - Injection in configAngular datepicker difference between onChange and onInputHow to use a custom .config filein MEANJSHow to change an element's class with JavaScript?Where can I find documentation on formatting a date in JavaScript?How to format a JavaScript dateWhat is the difference between angular-route and angular-ui-router?Angular Material Datepicker - show selected hoildaysAngular Material Date Picker FilterHow to change the datepicker calendra view in angular materialShow only year in angular material datepickerHow to change Angular Material Datepicker format in run-timeHow to change Angular Material Datepicker monthYearLabel format in run-time

Is CEO the "profession" with the most psychopaths?

What is the meaning of 'breadth' in breadth first search?

What to do with repeated rejections for phd position

Central Vacuuming: Is it worth it, and how does it compare to normal vacuuming?

Drawing spherical mirrors

Is there public access to the Meteor Crater in Arizona?

Is it fair for a professor to grade us on the possession of past papers?

Flash light on something

What's the point of the test set?

Is multiple magic items in one inherently imbalanced?

Dyck paths with extra diagonals from valleys (Laser construction)

Why weren't discrete x86 CPUs ever used in game hardware?

Crossing US/Canada Border for less than 24 hours

How does the math work when buying airline miles?

Co-worker has annoying ringtone

What is the difference between a "ranged attack" and a "ranged weapon attack"?

Can the Flaming Sphere spell be rammed into multiple Tiny creatures that are in the same 5-foot square?

How were pictures turned from film to a big picture in a picture frame before digital scanning?

Deconstruction is ambiguous

What makes a man succeed?

Random body shuffle every night—can we still function?

Karn the great creator - 'card from outside the game' in sealed

macOS: Name for app shortcut screen found by pinching with thumb and three fingers

Has negative voting ever been officially implemented in elections, or seriously proposed, or even studied?



Change format of md-datepicker in Angular Material with momentjs



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!AngularJS Material date picker date format not workingHow to format date in angularjsmd-datepicker input formati want set format of md-datepicker to dd-mm-yyyyChange md-datepicker ng-model formatFormat date in Angular JS material using model possible?How do I format Angular Material's md-datepicker for Django REST Framework?AngularJS - Injection in configAngular datepicker difference between onChange and onInputHow to use a custom .config filein MEANJSHow to change an element's class with JavaScript?Where can I find documentation on formatting a date in JavaScript?How to format a JavaScript dateWhat is the difference between angular-route and angular-ui-router?Angular Material Datepicker - show selected hoildaysAngular Material Date Picker FilterHow to change the datepicker calendra view in angular materialShow only year in angular material datepickerHow to change Angular Material Datepicker format in run-timeHow to change Angular Material Datepicker monthYearLabel format in run-time



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








57















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?










share|improve this question






























    57















    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?










    share|improve this question


























      57












      57








      57


      8






      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?










      share|improve this question
















      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?







      javascript angularjs localization angular-material momentjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 7 at 22:52









      mruanova

      1,99921435




      1,99921435










      asked Sep 14 '15 at 13:44









      dearn44dearn44

      1,22911537




      1,22911537






















          13 Answers
          13






          active

          oldest

          votes


















          93














          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.






          share|improve this answer

























          • This sets today's date to datepicker. I want it to be null on load. What should I do?

            – Ali Poder
            Oct 16 '15 at 16:30






          • 5





            @AliDemirci Assuming that the date you are binding to is undefined on load, something like this should work: return date ? moment(date).format('YYYY-MM-DD') : '';

            – Bohuslav Burghardt
            Oct 16 '15 at 16:55






          • 4





            thank you that works for input but it does not return me the formatted date on ng-model instead it gives me a date like Tue Oct 06 2015 00:00:00 GMT+0300

            – Ali Poder
            Oct 19 '15 at 8:15






          • 3





            Unfortunately it doesn't work if the date is typed from the keyboard. Eg. for the above format I'm typing 2016-04-01 which returns 4th January :/

            – kazuar
            Jan 4 '16 at 13:38






          • 1





            @saurabh, I have fixed it. my use-case is simply to send this date value back to the server, but our java-backend couldn't process it. so my backend dev asked me to send the date back without the ".***Z". And fortunately moment(question.date).format('YYYY-MM-DDTHH:mm:ss') did the trick for me. hope this helps

            – loveNZ
            Feb 12 '16 at 3:39


















          55














          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






          share|improve this answer























          • This worked fine for me, thanks.

            – Benny Bottema
            Jul 26 '16 at 8:56











          • This should probably be the accepted answer. If you're using moment, you'll also need to add it to your config params after $mdDateLocaleProvider as so: angular.module('app') .config(function ($mdDateLocaleProvider, moment) ... )

            – yjimk
            Oct 13 '16 at 21:45












          • While this code gets called, it doesn't seem to actually update the value.

            – mcv
            Dec 6 '16 at 14:27


















          20














          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;

          ;
          );





          share|improve this answer






























            7














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





            share|improve this answer























            • Does this need something extra? I tried it (without moment, though), and the code does get called, but the result doesn't end up in the model.

              – mcv
              Dec 6 '16 at 14:45











            • The moment.js is required.

              – Janderson Silva
              Dec 16 '16 at 20:58












            • I got this working without moment.js. In the component that uses it (rather than at config stage) I do: $mdDateLocale.formatDate = date => $filter('date')(date, "mediumDate"); The other direction is automatically handled by javascript's built in date parsing, which is extremely forgiving.

              – mcv
              Dec 18 '16 at 7:57


















            5














            Changing date format, month names and week names during runtime is perfectly possible with AngularJS 1.5.9 and moment 2.17.1.



            First configure the initial language. (In this example the configuration of angular-translate/$translateProvider is optional.)



            angular.module('app').config(configureLocalization)

            configureLocalization.$inject = ['$translateProvider', '$mdDateLocaleProvider', 'localdb', '__config'];
            function configureLocalization($translateProvider, $mdDateLocaleProvider, localdb, __config)


            Later you may have some base controller that watches a language variable which is changed when the user selects another language.



            angular.module('app').controller('BaseCtrl', Base);

            Base.$inject = ['$scope', '$translate', 'localdb', '$mdDateLocale'];
            function Base($scope, $translate, localdb, $mdDateLocale)

            var vm = this;
            vm.language = $translate.use();

            $scope.$watch('BaseCtrl.language', function(newValue, oldValue)
            // Set the new language in local storage
            localdb.set('language', newValue);
            $translate.use(newValue);

            // Change moment's locale so the 'L'-format is adjusted.
            // For example the 'L'-format is DD-MM-YYYY for Dutch
            moment.locale(newValue);

            // Set month and week names for the general $mdDateLocale service
            var localeDate = moment.localeData();
            $mdDateLocale.months = localeDate._months;
            $mdDateLocale.shortMonths = moment.monthsShort();
            $mdDateLocale.days = localeDate._weekdays;
            $mdDateLocale.shortDays = localeDate._weekdaysMin;
            // Optionaly let the week start on the day as defined by moment's locale data
            $mdDateLocale.firstDayOfWeek = localeData._week.dow;
            );



            Notice how we don't need to change the $mdDateLocale.formatDate and $mdDateLocale.parseDate methods as they are already configured to use the 'L'-format that is changed by calling moment.locale(newValue).



            See the documentation for $mdDateLocaleProvider for more locale customization: https://material.angularjs.org/latest/api/service/$mdDateLocaleProvider



            Bonus: This is how the language selector may look like:



            <md-select ng-model="BaseCtrl.language" class="md-no-underline">
            <md-option
            ng-repeat="language in ['en', 'de', 'fr', 'nl']"
            ng-value ="language"
            ><span
            class ="flag-icon flag-icon-language ==='en' ? 'gb' : language"
            ></span>
            </md-option>
            </md-select>





            share|improve this answer
































              4














              -- When we use md-DatePicker in md-dialog then $mdDateLocaleProvider service doesnot format the date as we need. We have to use $mdDateLocale in controller of md-dialog to format the date of md-DatePicker. for example -



              angular.module('MyApp').controller('AppCtrl', function($scope, $mdDateLocale) 

              $mdDateLocale.formatDate = function(date)
              return moment(date).format('YYYY-MM-DD');
              ;

              $scope.myDate = new Date('2015-10-15');

              $scope.minDate = new Date();

              $scope.maxDate = new Date();
              );





              share|improve this answer























              • How are you accessing moment inside controller?Dont you get any error?

                – Raphael
                Nov 24 '16 at 17:05











              • No sir, i didn't get any error. Just add moment.js reference in your index.html page like - <script src="Scripts/moment.min.js"></script> and it works for me.

                – Ravindra Vairagi
                Nov 26 '16 at 5:15











              • This is a fantastic solution if you would just like to override the format in 1 controller, and not others. Thank you - worked a treat!

                – user1191559
                Jul 20 '17 at 21:53


















              3














              Using $filter instead of moment.js and in reference to responses from @Ian Poston Framer and @java dev for me the following finally worked for me:



              angular
              .module('App', ['ngMaterial'])
              .run(function($mdDateLocale, $filter)
              $mdDateLocale.formatDate = function(date)
              return $filter('date')(date, "dd-MM-yyyy");
              ;
              )


              I couldn't inject $filter into.config because it's not a provider, so I had to do it inside .run with $mdDateLocale.






              share|improve this answer






























                2














                I had same problem and came up with this simple solution with the help of moment.js. I used ng-change attribute which fires when the date is changed.



                Inside your HTML:



                <md-datepicker ng-model="myDate" ng-change="dateChanged()"></md-datepicker>


                Inside your controller:



                $scope.dateChanged = function() 
                this.myDate = moment(this.myDate).format('YYYY/MM/DD');






                share|improve this answer






























                  1














                  I'd like to provide my solution that's 100% based off of Christiaan Westerbeek's post. I really like what he did, but I personally wanted something a bit more simplistic.



                  appConfig.js



                  // config params in global scope that need to be set outside of Angular (due to Angular limitiations)
                  var appConfig =
                  // enables the dynamic setting of md-datepicker display masks (eg. when user changes language from English to Spanish)
                  date:
                  // default mask
                  format: "MM/dd/yyyy",

                  // md-datepicker display format
                  mdFormatDate: function (date)
                  if (date && date instanceof Date)
                  return date.format(appConfig.date.format);

                  else
                  return null;







                  ;


                  app.material.config.js



                  // set angular material config
                  app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider)
                  // this is a global object set inside appConfig.js
                  $mdDateLocaleProvider.formatDate = appConfig.date.mdFormatDate;

                  ]);


                  some service file that deals with localization/translations/etc



                  // inside the service where you'd track the language/locale change
                  service._updateConfigDateFormat = function (theNewDateFormat)
                  // where theNewDateFormat is something like 'yyyy/MM/dd' or whatever
                  daepConfig.date.format = theNewDateFormat;

                  ;


                  It should be noted that this solution will not live re-format your md-datepicker's display values. It will only work when the model changes values.






                  share|improve this answer






























                    1














                    For angular-material >= 5.x.x



                    The recommended way of using other custom/predefined date formats is described in the angular material documentation:



                    https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings



                    An implementation example using MomentJS for customizing and parsing datetime display formats:



                    ...
                    import MomentModule from 'angular2-moment';

                    import MatMomentDateModule, MomentDateAdapter, MAT_MOMENT_DATE_FORMATS from '@angular/material-moment-adapter';
                    import DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE from '@angular/material/core';

                    ...

                    // moment formats explanation: https://momentjs.com/docs/#/displaying/format/
                    export const MY_FORMATS =
                    parse:
                    dateInput: 'YYYY-MM-DD',
                    ,
                    display:
                    dateInput: 'YYYY-MM-DD',
                    monthYearLabel: 'MMM YYYY',
                    dateA11yLabel: 'YYYY-MM-DD',
                    monthYearA11yLabel: 'MMMM YYYY',
                    ,
                    ;

                    ...

                    @Component(
                    ...
                    providers: [
                    // `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
                    // `MatMomentDateModule` in your applications root module. We provide it at the component level
                    // here, due to limitations of our example generation script.
                    provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE],
                    // provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS,
                    provide: MAT_DATE_FORMATS, useValue: MY_FORMATS
                    ]
                    )

                    ...


                    Depending on your implementation, inside the component you might also need to use:



                    date = new FormControl(moment());



                    You must also install Moment library and adapter for Angular:



                    https://www.npmjs.com/package/angular2-moment



                    npm install --save angular2-moment



                    https://www.npmjs.com/package/@angular/material-moment-adapter



                    npm install --save @angular/material-moment-adapter






                    share|improve this answer






























                      0














                      If you are using the latest version of angular-material.js then use the $mdDateLocale service. This code sample uses angular's built in date filter as an alternative to using the moment.js library. See other date format options using angular's $filter service here at this link https://docs.angularjs.org/api/ng/filter/date.



                      // mainController.js
                      angular.module('app').config(function($mdDateLocale, $filter, $scope)

                      // FORMAT THE DATE FOR THE DATEPICKER
                      $mdDateLocale.formatDate = function(date)
                      return $filter('date')($scope.myDate, "mediumDate");
                      ;

                      );





                      share|improve this answer






























                        0














                        I used $mdDateLocaleProvider to format it on the frond end. If you want to format date while sending it to the back end, the following worked for me :-



                        $filter('date')(this.date, 'MM/dd/yyyy');


                        I have the above in controller.






                        share|improve this answer
































                          0














                          in my case I was loosing the PlaceHolder everythig works but the placeHolder was disappearing when I use custom formatting. Below lines solved my problem with placeholder.



                          $mdDateLocaleProvider.formatDate = function (date) 
                          if(date==null)
                          return "";
                          var m = moment(date);
                          return m.isValid() ? m.format('L') : '';
                          ;





                          share|improve this answer























                            Your Answer






                            StackExchange.ifUsing("editor", function ()
                            StackExchange.using("externalEditor", function ()
                            StackExchange.using("snippets", function ()
                            StackExchange.snippets.init();
                            );
                            );
                            , "code-snippets");

                            StackExchange.ready(function()
                            var channelOptions =
                            tags: "".split(" "),
                            id: "1"
                            ;
                            initTagRenderer("".split(" "), "".split(" "), channelOptions);

                            StackExchange.using("externalEditor", function()
                            // Have to fire editor after snippets, if snippets enabled
                            if (StackExchange.settings.snippets.snippetsEnabled)
                            StackExchange.using("snippets", function()
                            createEditor();
                            );

                            else
                            createEditor();

                            );

                            function createEditor()
                            StackExchange.prepareEditor(
                            heartbeatType: 'answer',
                            autoActivateHeartbeat: false,
                            convertImagesToLinks: true,
                            noModals: true,
                            showLowRepImageUploadWarning: true,
                            reputationToPostImages: 10,
                            bindNavPrevention: true,
                            postfix: "",
                            imageUploader:
                            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                            allowUrls: true
                            ,
                            onDemand: true,
                            discardSelector: ".discard-answer"
                            ,immediatelyShowMarkdownHelp:true
                            );



                            );













                            draft saved

                            draft discarded


















                            StackExchange.ready(
                            function ()
                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32566416%2fchange-format-of-md-datepicker-in-angular-material-with-momentjs%23new-answer', 'question_page');

                            );

                            Post as a guest















                            Required, but never shown

























                            13 Answers
                            13






                            active

                            oldest

                            votes








                            13 Answers
                            13






                            active

                            oldest

                            votes









                            active

                            oldest

                            votes






                            active

                            oldest

                            votes









                            93














                            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.






                            share|improve this answer

























                            • This sets today's date to datepicker. I want it to be null on load. What should I do?

                              – Ali Poder
                              Oct 16 '15 at 16:30






                            • 5





                              @AliDemirci Assuming that the date you are binding to is undefined on load, something like this should work: return date ? moment(date).format('YYYY-MM-DD') : '';

                              – Bohuslav Burghardt
                              Oct 16 '15 at 16:55






                            • 4





                              thank you that works for input but it does not return me the formatted date on ng-model instead it gives me a date like Tue Oct 06 2015 00:00:00 GMT+0300

                              – Ali Poder
                              Oct 19 '15 at 8:15






                            • 3





                              Unfortunately it doesn't work if the date is typed from the keyboard. Eg. for the above format I'm typing 2016-04-01 which returns 4th January :/

                              – kazuar
                              Jan 4 '16 at 13:38






                            • 1





                              @saurabh, I have fixed it. my use-case is simply to send this date value back to the server, but our java-backend couldn't process it. so my backend dev asked me to send the date back without the ".***Z". And fortunately moment(question.date).format('YYYY-MM-DDTHH:mm:ss') did the trick for me. hope this helps

                              – loveNZ
                              Feb 12 '16 at 3:39















                            93














                            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.






                            share|improve this answer

























                            • This sets today's date to datepicker. I want it to be null on load. What should I do?

                              – Ali Poder
                              Oct 16 '15 at 16:30






                            • 5





                              @AliDemirci Assuming that the date you are binding to is undefined on load, something like this should work: return date ? moment(date).format('YYYY-MM-DD') : '';

                              – Bohuslav Burghardt
                              Oct 16 '15 at 16:55






                            • 4





                              thank you that works for input but it does not return me the formatted date on ng-model instead it gives me a date like Tue Oct 06 2015 00:00:00 GMT+0300

                              – Ali Poder
                              Oct 19 '15 at 8:15






                            • 3





                              Unfortunately it doesn't work if the date is typed from the keyboard. Eg. for the above format I'm typing 2016-04-01 which returns 4th January :/

                              – kazuar
                              Jan 4 '16 at 13:38






                            • 1





                              @saurabh, I have fixed it. my use-case is simply to send this date value back to the server, but our java-backend couldn't process it. so my backend dev asked me to send the date back without the ".***Z". And fortunately moment(question.date).format('YYYY-MM-DDTHH:mm:ss') did the trick for me. hope this helps

                              – loveNZ
                              Feb 12 '16 at 3:39













                            93












                            93








                            93







                            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.






                            share|improve this answer















                            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.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Dec 16 '16 at 18:36









                            Alexandre Bourlier

                            2,32333462




                            2,32333462










                            answered Sep 14 '15 at 13:55









                            Bohuslav BurghardtBohuslav Burghardt

                            23.2k27483




                            23.2k27483












                            • This sets today's date to datepicker. I want it to be null on load. What should I do?

                              – Ali Poder
                              Oct 16 '15 at 16:30






                            • 5





                              @AliDemirci Assuming that the date you are binding to is undefined on load, something like this should work: return date ? moment(date).format('YYYY-MM-DD') : '';

                              – Bohuslav Burghardt
                              Oct 16 '15 at 16:55






                            • 4





                              thank you that works for input but it does not return me the formatted date on ng-model instead it gives me a date like Tue Oct 06 2015 00:00:00 GMT+0300

                              – Ali Poder
                              Oct 19 '15 at 8:15






                            • 3





                              Unfortunately it doesn't work if the date is typed from the keyboard. Eg. for the above format I'm typing 2016-04-01 which returns 4th January :/

                              – kazuar
                              Jan 4 '16 at 13:38






                            • 1





                              @saurabh, I have fixed it. my use-case is simply to send this date value back to the server, but our java-backend couldn't process it. so my backend dev asked me to send the date back without the ".***Z". And fortunately moment(question.date).format('YYYY-MM-DDTHH:mm:ss') did the trick for me. hope this helps

                              – loveNZ
                              Feb 12 '16 at 3:39

















                            • This sets today's date to datepicker. I want it to be null on load. What should I do?

                              – Ali Poder
                              Oct 16 '15 at 16:30






                            • 5





                              @AliDemirci Assuming that the date you are binding to is undefined on load, something like this should work: return date ? moment(date).format('YYYY-MM-DD') : '';

                              – Bohuslav Burghardt
                              Oct 16 '15 at 16:55






                            • 4





                              thank you that works for input but it does not return me the formatted date on ng-model instead it gives me a date like Tue Oct 06 2015 00:00:00 GMT+0300

                              – Ali Poder
                              Oct 19 '15 at 8:15






                            • 3





                              Unfortunately it doesn't work if the date is typed from the keyboard. Eg. for the above format I'm typing 2016-04-01 which returns 4th January :/

                              – kazuar
                              Jan 4 '16 at 13:38






                            • 1





                              @saurabh, I have fixed it. my use-case is simply to send this date value back to the server, but our java-backend couldn't process it. so my backend dev asked me to send the date back without the ".***Z". And fortunately moment(question.date).format('YYYY-MM-DDTHH:mm:ss') did the trick for me. hope this helps

                              – loveNZ
                              Feb 12 '16 at 3:39
















                            This sets today's date to datepicker. I want it to be null on load. What should I do?

                            – Ali Poder
                            Oct 16 '15 at 16:30





                            This sets today's date to datepicker. I want it to be null on load. What should I do?

                            – Ali Poder
                            Oct 16 '15 at 16:30




                            5




                            5





                            @AliDemirci Assuming that the date you are binding to is undefined on load, something like this should work: return date ? moment(date).format('YYYY-MM-DD') : '';

                            – Bohuslav Burghardt
                            Oct 16 '15 at 16:55





                            @AliDemirci Assuming that the date you are binding to is undefined on load, something like this should work: return date ? moment(date).format('YYYY-MM-DD') : '';

                            – Bohuslav Burghardt
                            Oct 16 '15 at 16:55




                            4




                            4





                            thank you that works for input but it does not return me the formatted date on ng-model instead it gives me a date like Tue Oct 06 2015 00:00:00 GMT+0300

                            – Ali Poder
                            Oct 19 '15 at 8:15





                            thank you that works for input but it does not return me the formatted date on ng-model instead it gives me a date like Tue Oct 06 2015 00:00:00 GMT+0300

                            – Ali Poder
                            Oct 19 '15 at 8:15




                            3




                            3





                            Unfortunately it doesn't work if the date is typed from the keyboard. Eg. for the above format I'm typing 2016-04-01 which returns 4th January :/

                            – kazuar
                            Jan 4 '16 at 13:38





                            Unfortunately it doesn't work if the date is typed from the keyboard. Eg. for the above format I'm typing 2016-04-01 which returns 4th January :/

                            – kazuar
                            Jan 4 '16 at 13:38




                            1




                            1





                            @saurabh, I have fixed it. my use-case is simply to send this date value back to the server, but our java-backend couldn't process it. so my backend dev asked me to send the date back without the ".***Z". And fortunately moment(question.date).format('YYYY-MM-DDTHH:mm:ss') did the trick for me. hope this helps

                            – loveNZ
                            Feb 12 '16 at 3:39





                            @saurabh, I have fixed it. my use-case is simply to send this date value back to the server, but our java-backend couldn't process it. so my backend dev asked me to send the date back without the ".***Z". And fortunately moment(question.date).format('YYYY-MM-DDTHH:mm:ss') did the trick for me. hope this helps

                            – loveNZ
                            Feb 12 '16 at 3:39













                            55














                            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






                            share|improve this answer























                            • This worked fine for me, thanks.

                              – Benny Bottema
                              Jul 26 '16 at 8:56











                            • This should probably be the accepted answer. If you're using moment, you'll also need to add it to your config params after $mdDateLocaleProvider as so: angular.module('app') .config(function ($mdDateLocaleProvider, moment) ... )

                              – yjimk
                              Oct 13 '16 at 21:45












                            • While this code gets called, it doesn't seem to actually update the value.

                              – mcv
                              Dec 6 '16 at 14:27















                            55














                            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






                            share|improve this answer























                            • This worked fine for me, thanks.

                              – Benny Bottema
                              Jul 26 '16 at 8:56











                            • This should probably be the accepted answer. If you're using moment, you'll also need to add it to your config params after $mdDateLocaleProvider as so: angular.module('app') .config(function ($mdDateLocaleProvider, moment) ... )

                              – yjimk
                              Oct 13 '16 at 21:45












                            • While this code gets called, it doesn't seem to actually update the value.

                              – mcv
                              Dec 6 '16 at 14:27













                            55












                            55








                            55







                            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






                            share|improve this answer













                            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







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 7 '16 at 11:50









                            shulitoshulito

                            69159




                            69159












                            • This worked fine for me, thanks.

                              – Benny Bottema
                              Jul 26 '16 at 8:56











                            • This should probably be the accepted answer. If you're using moment, you'll also need to add it to your config params after $mdDateLocaleProvider as so: angular.module('app') .config(function ($mdDateLocaleProvider, moment) ... )

                              – yjimk
                              Oct 13 '16 at 21:45












                            • While this code gets called, it doesn't seem to actually update the value.

                              – mcv
                              Dec 6 '16 at 14:27

















                            • This worked fine for me, thanks.

                              – Benny Bottema
                              Jul 26 '16 at 8:56











                            • This should probably be the accepted answer. If you're using moment, you'll also need to add it to your config params after $mdDateLocaleProvider as so: angular.module('app') .config(function ($mdDateLocaleProvider, moment) ... )

                              – yjimk
                              Oct 13 '16 at 21:45












                            • While this code gets called, it doesn't seem to actually update the value.

                              – mcv
                              Dec 6 '16 at 14:27
















                            This worked fine for me, thanks.

                            – Benny Bottema
                            Jul 26 '16 at 8:56





                            This worked fine for me, thanks.

                            – Benny Bottema
                            Jul 26 '16 at 8:56













                            This should probably be the accepted answer. If you're using moment, you'll also need to add it to your config params after $mdDateLocaleProvider as so: angular.module('app') .config(function ($mdDateLocaleProvider, moment) ... )

                            – yjimk
                            Oct 13 '16 at 21:45






                            This should probably be the accepted answer. If you're using moment, you'll also need to add it to your config params after $mdDateLocaleProvider as so: angular.module('app') .config(function ($mdDateLocaleProvider, moment) ... )

                            – yjimk
                            Oct 13 '16 at 21:45














                            While this code gets called, it doesn't seem to actually update the value.

                            – mcv
                            Dec 6 '16 at 14:27





                            While this code gets called, it doesn't seem to actually update the value.

                            – mcv
                            Dec 6 '16 at 14:27











                            20














                            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;

                            ;
                            );





                            share|improve this answer



























                              20














                              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;

                              ;
                              );





                              share|improve this answer

























                                20












                                20








                                20







                                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;

                                ;
                                );





                                share|improve this answer













                                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;

                                ;
                                );






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Sep 1 '16 at 10:32









                                Ben TaliadorosBen Taliadoros

                                3,163114575




                                3,163114575





















                                    7














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





                                    share|improve this answer























                                    • Does this need something extra? I tried it (without moment, though), and the code does get called, but the result doesn't end up in the model.

                                      – mcv
                                      Dec 6 '16 at 14:45











                                    • The moment.js is required.

                                      – Janderson Silva
                                      Dec 16 '16 at 20:58












                                    • I got this working without moment.js. In the component that uses it (rather than at config stage) I do: $mdDateLocale.formatDate = date => $filter('date')(date, "mediumDate"); The other direction is automatically handled by javascript's built in date parsing, which is extremely forgiving.

                                      – mcv
                                      Dec 18 '16 at 7:57















                                    7














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





                                    share|improve this answer























                                    • Does this need something extra? I tried it (without moment, though), and the code does get called, but the result doesn't end up in the model.

                                      – mcv
                                      Dec 6 '16 at 14:45











                                    • The moment.js is required.

                                      – Janderson Silva
                                      Dec 16 '16 at 20:58












                                    • I got this working without moment.js. In the component that uses it (rather than at config stage) I do: $mdDateLocale.formatDate = date => $filter('date')(date, "mediumDate"); The other direction is automatically handled by javascript's built in date parsing, which is extremely forgiving.

                                      – mcv
                                      Dec 18 '16 at 7:57













                                    7












                                    7








                                    7







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





                                    share|improve this answer













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






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Aug 4 '16 at 19:25









                                    Janderson SilvaJanderson Silva

                                    9691012




                                    9691012












                                    • Does this need something extra? I tried it (without moment, though), and the code does get called, but the result doesn't end up in the model.

                                      – mcv
                                      Dec 6 '16 at 14:45











                                    • The moment.js is required.

                                      – Janderson Silva
                                      Dec 16 '16 at 20:58












                                    • I got this working without moment.js. In the component that uses it (rather than at config stage) I do: $mdDateLocale.formatDate = date => $filter('date')(date, "mediumDate"); The other direction is automatically handled by javascript's built in date parsing, which is extremely forgiving.

                                      – mcv
                                      Dec 18 '16 at 7:57

















                                    • Does this need something extra? I tried it (without moment, though), and the code does get called, but the result doesn't end up in the model.

                                      – mcv
                                      Dec 6 '16 at 14:45











                                    • The moment.js is required.

                                      – Janderson Silva
                                      Dec 16 '16 at 20:58












                                    • I got this working without moment.js. In the component that uses it (rather than at config stage) I do: $mdDateLocale.formatDate = date => $filter('date')(date, "mediumDate"); The other direction is automatically handled by javascript's built in date parsing, which is extremely forgiving.

                                      – mcv
                                      Dec 18 '16 at 7:57
















                                    Does this need something extra? I tried it (without moment, though), and the code does get called, but the result doesn't end up in the model.

                                    – mcv
                                    Dec 6 '16 at 14:45





                                    Does this need something extra? I tried it (without moment, though), and the code does get called, but the result doesn't end up in the model.

                                    – mcv
                                    Dec 6 '16 at 14:45













                                    The moment.js is required.

                                    – Janderson Silva
                                    Dec 16 '16 at 20:58






                                    The moment.js is required.

                                    – Janderson Silva
                                    Dec 16 '16 at 20:58














                                    I got this working without moment.js. In the component that uses it (rather than at config stage) I do: $mdDateLocale.formatDate = date => $filter('date')(date, "mediumDate"); The other direction is automatically handled by javascript's built in date parsing, which is extremely forgiving.

                                    – mcv
                                    Dec 18 '16 at 7:57





                                    I got this working without moment.js. In the component that uses it (rather than at config stage) I do: $mdDateLocale.formatDate = date => $filter('date')(date, "mediumDate"); The other direction is automatically handled by javascript's built in date parsing, which is extremely forgiving.

                                    – mcv
                                    Dec 18 '16 at 7:57











                                    5














                                    Changing date format, month names and week names during runtime is perfectly possible with AngularJS 1.5.9 and moment 2.17.1.



                                    First configure the initial language. (In this example the configuration of angular-translate/$translateProvider is optional.)



                                    angular.module('app').config(configureLocalization)

                                    configureLocalization.$inject = ['$translateProvider', '$mdDateLocaleProvider', 'localdb', '__config'];
                                    function configureLocalization($translateProvider, $mdDateLocaleProvider, localdb, __config)


                                    Later you may have some base controller that watches a language variable which is changed when the user selects another language.



                                    angular.module('app').controller('BaseCtrl', Base);

                                    Base.$inject = ['$scope', '$translate', 'localdb', '$mdDateLocale'];
                                    function Base($scope, $translate, localdb, $mdDateLocale)

                                    var vm = this;
                                    vm.language = $translate.use();

                                    $scope.$watch('BaseCtrl.language', function(newValue, oldValue)
                                    // Set the new language in local storage
                                    localdb.set('language', newValue);
                                    $translate.use(newValue);

                                    // Change moment's locale so the 'L'-format is adjusted.
                                    // For example the 'L'-format is DD-MM-YYYY for Dutch
                                    moment.locale(newValue);

                                    // Set month and week names for the general $mdDateLocale service
                                    var localeDate = moment.localeData();
                                    $mdDateLocale.months = localeDate._months;
                                    $mdDateLocale.shortMonths = moment.monthsShort();
                                    $mdDateLocale.days = localeDate._weekdays;
                                    $mdDateLocale.shortDays = localeDate._weekdaysMin;
                                    // Optionaly let the week start on the day as defined by moment's locale data
                                    $mdDateLocale.firstDayOfWeek = localeData._week.dow;
                                    );



                                    Notice how we don't need to change the $mdDateLocale.formatDate and $mdDateLocale.parseDate methods as they are already configured to use the 'L'-format that is changed by calling moment.locale(newValue).



                                    See the documentation for $mdDateLocaleProvider for more locale customization: https://material.angularjs.org/latest/api/service/$mdDateLocaleProvider



                                    Bonus: This is how the language selector may look like:



                                    <md-select ng-model="BaseCtrl.language" class="md-no-underline">
                                    <md-option
                                    ng-repeat="language in ['en', 'de', 'fr', 'nl']"
                                    ng-value ="language"
                                    ><span
                                    class ="flag-icon flag-icon-language ==='en' ? 'gb' : language"
                                    ></span>
                                    </md-option>
                                    </md-select>





                                    share|improve this answer





























                                      5














                                      Changing date format, month names and week names during runtime is perfectly possible with AngularJS 1.5.9 and moment 2.17.1.



                                      First configure the initial language. (In this example the configuration of angular-translate/$translateProvider is optional.)



                                      angular.module('app').config(configureLocalization)

                                      configureLocalization.$inject = ['$translateProvider', '$mdDateLocaleProvider', 'localdb', '__config'];
                                      function configureLocalization($translateProvider, $mdDateLocaleProvider, localdb, __config)


                                      Later you may have some base controller that watches a language variable which is changed when the user selects another language.



                                      angular.module('app').controller('BaseCtrl', Base);

                                      Base.$inject = ['$scope', '$translate', 'localdb', '$mdDateLocale'];
                                      function Base($scope, $translate, localdb, $mdDateLocale)

                                      var vm = this;
                                      vm.language = $translate.use();

                                      $scope.$watch('BaseCtrl.language', function(newValue, oldValue)
                                      // Set the new language in local storage
                                      localdb.set('language', newValue);
                                      $translate.use(newValue);

                                      // Change moment's locale so the 'L'-format is adjusted.
                                      // For example the 'L'-format is DD-MM-YYYY for Dutch
                                      moment.locale(newValue);

                                      // Set month and week names for the general $mdDateLocale service
                                      var localeDate = moment.localeData();
                                      $mdDateLocale.months = localeDate._months;
                                      $mdDateLocale.shortMonths = moment.monthsShort();
                                      $mdDateLocale.days = localeDate._weekdays;
                                      $mdDateLocale.shortDays = localeDate._weekdaysMin;
                                      // Optionaly let the week start on the day as defined by moment's locale data
                                      $mdDateLocale.firstDayOfWeek = localeData._week.dow;
                                      );



                                      Notice how we don't need to change the $mdDateLocale.formatDate and $mdDateLocale.parseDate methods as they are already configured to use the 'L'-format that is changed by calling moment.locale(newValue).



                                      See the documentation for $mdDateLocaleProvider for more locale customization: https://material.angularjs.org/latest/api/service/$mdDateLocaleProvider



                                      Bonus: This is how the language selector may look like:



                                      <md-select ng-model="BaseCtrl.language" class="md-no-underline">
                                      <md-option
                                      ng-repeat="language in ['en', 'de', 'fr', 'nl']"
                                      ng-value ="language"
                                      ><span
                                      class ="flag-icon flag-icon-language ==='en' ? 'gb' : language"
                                      ></span>
                                      </md-option>
                                      </md-select>





                                      share|improve this answer



























                                        5












                                        5








                                        5







                                        Changing date format, month names and week names during runtime is perfectly possible with AngularJS 1.5.9 and moment 2.17.1.



                                        First configure the initial language. (In this example the configuration of angular-translate/$translateProvider is optional.)



                                        angular.module('app').config(configureLocalization)

                                        configureLocalization.$inject = ['$translateProvider', '$mdDateLocaleProvider', 'localdb', '__config'];
                                        function configureLocalization($translateProvider, $mdDateLocaleProvider, localdb, __config)


                                        Later you may have some base controller that watches a language variable which is changed when the user selects another language.



                                        angular.module('app').controller('BaseCtrl', Base);

                                        Base.$inject = ['$scope', '$translate', 'localdb', '$mdDateLocale'];
                                        function Base($scope, $translate, localdb, $mdDateLocale)

                                        var vm = this;
                                        vm.language = $translate.use();

                                        $scope.$watch('BaseCtrl.language', function(newValue, oldValue)
                                        // Set the new language in local storage
                                        localdb.set('language', newValue);
                                        $translate.use(newValue);

                                        // Change moment's locale so the 'L'-format is adjusted.
                                        // For example the 'L'-format is DD-MM-YYYY for Dutch
                                        moment.locale(newValue);

                                        // Set month and week names for the general $mdDateLocale service
                                        var localeDate = moment.localeData();
                                        $mdDateLocale.months = localeDate._months;
                                        $mdDateLocale.shortMonths = moment.monthsShort();
                                        $mdDateLocale.days = localeDate._weekdays;
                                        $mdDateLocale.shortDays = localeDate._weekdaysMin;
                                        // Optionaly let the week start on the day as defined by moment's locale data
                                        $mdDateLocale.firstDayOfWeek = localeData._week.dow;
                                        );



                                        Notice how we don't need to change the $mdDateLocale.formatDate and $mdDateLocale.parseDate methods as they are already configured to use the 'L'-format that is changed by calling moment.locale(newValue).



                                        See the documentation for $mdDateLocaleProvider for more locale customization: https://material.angularjs.org/latest/api/service/$mdDateLocaleProvider



                                        Bonus: This is how the language selector may look like:



                                        <md-select ng-model="BaseCtrl.language" class="md-no-underline">
                                        <md-option
                                        ng-repeat="language in ['en', 'de', 'fr', 'nl']"
                                        ng-value ="language"
                                        ><span
                                        class ="flag-icon flag-icon-language ==='en' ? 'gb' : language"
                                        ></span>
                                        </md-option>
                                        </md-select>





                                        share|improve this answer















                                        Changing date format, month names and week names during runtime is perfectly possible with AngularJS 1.5.9 and moment 2.17.1.



                                        First configure the initial language. (In this example the configuration of angular-translate/$translateProvider is optional.)



                                        angular.module('app').config(configureLocalization)

                                        configureLocalization.$inject = ['$translateProvider', '$mdDateLocaleProvider', 'localdb', '__config'];
                                        function configureLocalization($translateProvider, $mdDateLocaleProvider, localdb, __config)


                                        Later you may have some base controller that watches a language variable which is changed when the user selects another language.



                                        angular.module('app').controller('BaseCtrl', Base);

                                        Base.$inject = ['$scope', '$translate', 'localdb', '$mdDateLocale'];
                                        function Base($scope, $translate, localdb, $mdDateLocale)

                                        var vm = this;
                                        vm.language = $translate.use();

                                        $scope.$watch('BaseCtrl.language', function(newValue, oldValue)
                                        // Set the new language in local storage
                                        localdb.set('language', newValue);
                                        $translate.use(newValue);

                                        // Change moment's locale so the 'L'-format is adjusted.
                                        // For example the 'L'-format is DD-MM-YYYY for Dutch
                                        moment.locale(newValue);

                                        // Set month and week names for the general $mdDateLocale service
                                        var localeDate = moment.localeData();
                                        $mdDateLocale.months = localeDate._months;
                                        $mdDateLocale.shortMonths = moment.monthsShort();
                                        $mdDateLocale.days = localeDate._weekdays;
                                        $mdDateLocale.shortDays = localeDate._weekdaysMin;
                                        // Optionaly let the week start on the day as defined by moment's locale data
                                        $mdDateLocale.firstDayOfWeek = localeData._week.dow;
                                        );



                                        Notice how we don't need to change the $mdDateLocale.formatDate and $mdDateLocale.parseDate methods as they are already configured to use the 'L'-format that is changed by calling moment.locale(newValue).



                                        See the documentation for $mdDateLocaleProvider for more locale customization: https://material.angularjs.org/latest/api/service/$mdDateLocaleProvider



                                        Bonus: This is how the language selector may look like:



                                        <md-select ng-model="BaseCtrl.language" class="md-no-underline">
                                        <md-option
                                        ng-repeat="language in ['en', 'de', 'fr', 'nl']"
                                        ng-value ="language"
                                        ><span
                                        class ="flag-icon flag-icon-language ==='en' ? 'gb' : language"
                                        ></span>
                                        </md-option>
                                        </md-select>






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Apr 14 '17 at 10:47

























                                        answered Apr 14 '17 at 9:38









                                        Christiaan WesterbeekChristiaan Westerbeek

                                        5,80394161




                                        5,80394161





















                                            4














                                            -- When we use md-DatePicker in md-dialog then $mdDateLocaleProvider service doesnot format the date as we need. We have to use $mdDateLocale in controller of md-dialog to format the date of md-DatePicker. for example -



                                            angular.module('MyApp').controller('AppCtrl', function($scope, $mdDateLocale) 

                                            $mdDateLocale.formatDate = function(date)
                                            return moment(date).format('YYYY-MM-DD');
                                            ;

                                            $scope.myDate = new Date('2015-10-15');

                                            $scope.minDate = new Date();

                                            $scope.maxDate = new Date();
                                            );





                                            share|improve this answer























                                            • How are you accessing moment inside controller?Dont you get any error?

                                              – Raphael
                                              Nov 24 '16 at 17:05











                                            • No sir, i didn't get any error. Just add moment.js reference in your index.html page like - <script src="Scripts/moment.min.js"></script> and it works for me.

                                              – Ravindra Vairagi
                                              Nov 26 '16 at 5:15











                                            • This is a fantastic solution if you would just like to override the format in 1 controller, and not others. Thank you - worked a treat!

                                              – user1191559
                                              Jul 20 '17 at 21:53















                                            4














                                            -- When we use md-DatePicker in md-dialog then $mdDateLocaleProvider service doesnot format the date as we need. We have to use $mdDateLocale in controller of md-dialog to format the date of md-DatePicker. for example -



                                            angular.module('MyApp').controller('AppCtrl', function($scope, $mdDateLocale) 

                                            $mdDateLocale.formatDate = function(date)
                                            return moment(date).format('YYYY-MM-DD');
                                            ;

                                            $scope.myDate = new Date('2015-10-15');

                                            $scope.minDate = new Date();

                                            $scope.maxDate = new Date();
                                            );





                                            share|improve this answer























                                            • How are you accessing moment inside controller?Dont you get any error?

                                              – Raphael
                                              Nov 24 '16 at 17:05











                                            • No sir, i didn't get any error. Just add moment.js reference in your index.html page like - <script src="Scripts/moment.min.js"></script> and it works for me.

                                              – Ravindra Vairagi
                                              Nov 26 '16 at 5:15











                                            • This is a fantastic solution if you would just like to override the format in 1 controller, and not others. Thank you - worked a treat!

                                              – user1191559
                                              Jul 20 '17 at 21:53













                                            4












                                            4








                                            4







                                            -- When we use md-DatePicker in md-dialog then $mdDateLocaleProvider service doesnot format the date as we need. We have to use $mdDateLocale in controller of md-dialog to format the date of md-DatePicker. for example -



                                            angular.module('MyApp').controller('AppCtrl', function($scope, $mdDateLocale) 

                                            $mdDateLocale.formatDate = function(date)
                                            return moment(date).format('YYYY-MM-DD');
                                            ;

                                            $scope.myDate = new Date('2015-10-15');

                                            $scope.minDate = new Date();

                                            $scope.maxDate = new Date();
                                            );





                                            share|improve this answer













                                            -- When we use md-DatePicker in md-dialog then $mdDateLocaleProvider service doesnot format the date as we need. We have to use $mdDateLocale in controller of md-dialog to format the date of md-DatePicker. for example -



                                            angular.module('MyApp').controller('AppCtrl', function($scope, $mdDateLocale) 

                                            $mdDateLocale.formatDate = function(date)
                                            return moment(date).format('YYYY-MM-DD');
                                            ;

                                            $scope.myDate = new Date('2015-10-15');

                                            $scope.minDate = new Date();

                                            $scope.maxDate = new Date();
                                            );






                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Sep 24 '16 at 6:14









                                            Ravindra VairagiRavindra Vairagi

                                            406415




                                            406415












                                            • How are you accessing moment inside controller?Dont you get any error?

                                              – Raphael
                                              Nov 24 '16 at 17:05











                                            • No sir, i didn't get any error. Just add moment.js reference in your index.html page like - <script src="Scripts/moment.min.js"></script> and it works for me.

                                              – Ravindra Vairagi
                                              Nov 26 '16 at 5:15











                                            • This is a fantastic solution if you would just like to override the format in 1 controller, and not others. Thank you - worked a treat!

                                              – user1191559
                                              Jul 20 '17 at 21:53

















                                            • How are you accessing moment inside controller?Dont you get any error?

                                              – Raphael
                                              Nov 24 '16 at 17:05











                                            • No sir, i didn't get any error. Just add moment.js reference in your index.html page like - <script src="Scripts/moment.min.js"></script> and it works for me.

                                              – Ravindra Vairagi
                                              Nov 26 '16 at 5:15











                                            • This is a fantastic solution if you would just like to override the format in 1 controller, and not others. Thank you - worked a treat!

                                              – user1191559
                                              Jul 20 '17 at 21:53
















                                            How are you accessing moment inside controller?Dont you get any error?

                                            – Raphael
                                            Nov 24 '16 at 17:05





                                            How are you accessing moment inside controller?Dont you get any error?

                                            – Raphael
                                            Nov 24 '16 at 17:05













                                            No sir, i didn't get any error. Just add moment.js reference in your index.html page like - <script src="Scripts/moment.min.js"></script> and it works for me.

                                            – Ravindra Vairagi
                                            Nov 26 '16 at 5:15





                                            No sir, i didn't get any error. Just add moment.js reference in your index.html page like - <script src="Scripts/moment.min.js"></script> and it works for me.

                                            – Ravindra Vairagi
                                            Nov 26 '16 at 5:15













                                            This is a fantastic solution if you would just like to override the format in 1 controller, and not others. Thank you - worked a treat!

                                            – user1191559
                                            Jul 20 '17 at 21:53





                                            This is a fantastic solution if you would just like to override the format in 1 controller, and not others. Thank you - worked a treat!

                                            – user1191559
                                            Jul 20 '17 at 21:53











                                            3














                                            Using $filter instead of moment.js and in reference to responses from @Ian Poston Framer and @java dev for me the following finally worked for me:



                                            angular
                                            .module('App', ['ngMaterial'])
                                            .run(function($mdDateLocale, $filter)
                                            $mdDateLocale.formatDate = function(date)
                                            return $filter('date')(date, "dd-MM-yyyy");
                                            ;
                                            )


                                            I couldn't inject $filter into.config because it's not a provider, so I had to do it inside .run with $mdDateLocale.






                                            share|improve this answer



























                                              3














                                              Using $filter instead of moment.js and in reference to responses from @Ian Poston Framer and @java dev for me the following finally worked for me:



                                              angular
                                              .module('App', ['ngMaterial'])
                                              .run(function($mdDateLocale, $filter)
                                              $mdDateLocale.formatDate = function(date)
                                              return $filter('date')(date, "dd-MM-yyyy");
                                              ;
                                              )


                                              I couldn't inject $filter into.config because it's not a provider, so I had to do it inside .run with $mdDateLocale.






                                              share|improve this answer

























                                                3












                                                3








                                                3







                                                Using $filter instead of moment.js and in reference to responses from @Ian Poston Framer and @java dev for me the following finally worked for me:



                                                angular
                                                .module('App', ['ngMaterial'])
                                                .run(function($mdDateLocale, $filter)
                                                $mdDateLocale.formatDate = function(date)
                                                return $filter('date')(date, "dd-MM-yyyy");
                                                ;
                                                )


                                                I couldn't inject $filter into.config because it's not a provider, so I had to do it inside .run with $mdDateLocale.






                                                share|improve this answer













                                                Using $filter instead of moment.js and in reference to responses from @Ian Poston Framer and @java dev for me the following finally worked for me:



                                                angular
                                                .module('App', ['ngMaterial'])
                                                .run(function($mdDateLocale, $filter)
                                                $mdDateLocale.formatDate = function(date)
                                                return $filter('date')(date, "dd-MM-yyyy");
                                                ;
                                                )


                                                I couldn't inject $filter into.config because it's not a provider, so I had to do it inside .run with $mdDateLocale.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Sep 17 '17 at 4:40









                                                marcinowskimarcinowski

                                                13423




                                                13423





















                                                    2














                                                    I had same problem and came up with this simple solution with the help of moment.js. I used ng-change attribute which fires when the date is changed.



                                                    Inside your HTML:



                                                    <md-datepicker ng-model="myDate" ng-change="dateChanged()"></md-datepicker>


                                                    Inside your controller:



                                                    $scope.dateChanged = function() 
                                                    this.myDate = moment(this.myDate).format('YYYY/MM/DD');






                                                    share|improve this answer



























                                                      2














                                                      I had same problem and came up with this simple solution with the help of moment.js. I used ng-change attribute which fires when the date is changed.



                                                      Inside your HTML:



                                                      <md-datepicker ng-model="myDate" ng-change="dateChanged()"></md-datepicker>


                                                      Inside your controller:



                                                      $scope.dateChanged = function() 
                                                      this.myDate = moment(this.myDate).format('YYYY/MM/DD');






                                                      share|improve this answer

























                                                        2












                                                        2








                                                        2







                                                        I had same problem and came up with this simple solution with the help of moment.js. I used ng-change attribute which fires when the date is changed.



                                                        Inside your HTML:



                                                        <md-datepicker ng-model="myDate" ng-change="dateChanged()"></md-datepicker>


                                                        Inside your controller:



                                                        $scope.dateChanged = function() 
                                                        this.myDate = moment(this.myDate).format('YYYY/MM/DD');






                                                        share|improve this answer













                                                        I had same problem and came up with this simple solution with the help of moment.js. I used ng-change attribute which fires when the date is changed.



                                                        Inside your HTML:



                                                        <md-datepicker ng-model="myDate" ng-change="dateChanged()"></md-datepicker>


                                                        Inside your controller:



                                                        $scope.dateChanged = function() 
                                                        this.myDate = moment(this.myDate).format('YYYY/MM/DD');







                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Feb 4 '18 at 7:22









                                                        ttvd94ttvd94

                                                        879




                                                        879





















                                                            1














                                                            I'd like to provide my solution that's 100% based off of Christiaan Westerbeek's post. I really like what he did, but I personally wanted something a bit more simplistic.



                                                            appConfig.js



                                                            // config params in global scope that need to be set outside of Angular (due to Angular limitiations)
                                                            var appConfig =
                                                            // enables the dynamic setting of md-datepicker display masks (eg. when user changes language from English to Spanish)
                                                            date:
                                                            // default mask
                                                            format: "MM/dd/yyyy",

                                                            // md-datepicker display format
                                                            mdFormatDate: function (date)
                                                            if (date && date instanceof Date)
                                                            return date.format(appConfig.date.format);

                                                            else
                                                            return null;







                                                            ;


                                                            app.material.config.js



                                                            // set angular material config
                                                            app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider)
                                                            // this is a global object set inside appConfig.js
                                                            $mdDateLocaleProvider.formatDate = appConfig.date.mdFormatDate;

                                                            ]);


                                                            some service file that deals with localization/translations/etc



                                                            // inside the service where you'd track the language/locale change
                                                            service._updateConfigDateFormat = function (theNewDateFormat)
                                                            // where theNewDateFormat is something like 'yyyy/MM/dd' or whatever
                                                            daepConfig.date.format = theNewDateFormat;

                                                            ;


                                                            It should be noted that this solution will not live re-format your md-datepicker's display values. It will only work when the model changes values.






                                                            share|improve this answer



























                                                              1














                                                              I'd like to provide my solution that's 100% based off of Christiaan Westerbeek's post. I really like what he did, but I personally wanted something a bit more simplistic.



                                                              appConfig.js



                                                              // config params in global scope that need to be set outside of Angular (due to Angular limitiations)
                                                              var appConfig =
                                                              // enables the dynamic setting of md-datepicker display masks (eg. when user changes language from English to Spanish)
                                                              date:
                                                              // default mask
                                                              format: "MM/dd/yyyy",

                                                              // md-datepicker display format
                                                              mdFormatDate: function (date)
                                                              if (date && date instanceof Date)
                                                              return date.format(appConfig.date.format);

                                                              else
                                                              return null;







                                                              ;


                                                              app.material.config.js



                                                              // set angular material config
                                                              app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider)
                                                              // this is a global object set inside appConfig.js
                                                              $mdDateLocaleProvider.formatDate = appConfig.date.mdFormatDate;

                                                              ]);


                                                              some service file that deals with localization/translations/etc



                                                              // inside the service where you'd track the language/locale change
                                                              service._updateConfigDateFormat = function (theNewDateFormat)
                                                              // where theNewDateFormat is something like 'yyyy/MM/dd' or whatever
                                                              daepConfig.date.format = theNewDateFormat;

                                                              ;


                                                              It should be noted that this solution will not live re-format your md-datepicker's display values. It will only work when the model changes values.






                                                              share|improve this answer

























                                                                1












                                                                1








                                                                1







                                                                I'd like to provide my solution that's 100% based off of Christiaan Westerbeek's post. I really like what he did, but I personally wanted something a bit more simplistic.



                                                                appConfig.js



                                                                // config params in global scope that need to be set outside of Angular (due to Angular limitiations)
                                                                var appConfig =
                                                                // enables the dynamic setting of md-datepicker display masks (eg. when user changes language from English to Spanish)
                                                                date:
                                                                // default mask
                                                                format: "MM/dd/yyyy",

                                                                // md-datepicker display format
                                                                mdFormatDate: function (date)
                                                                if (date && date instanceof Date)
                                                                return date.format(appConfig.date.format);

                                                                else
                                                                return null;







                                                                ;


                                                                app.material.config.js



                                                                // set angular material config
                                                                app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider)
                                                                // this is a global object set inside appConfig.js
                                                                $mdDateLocaleProvider.formatDate = appConfig.date.mdFormatDate;

                                                                ]);


                                                                some service file that deals with localization/translations/etc



                                                                // inside the service where you'd track the language/locale change
                                                                service._updateConfigDateFormat = function (theNewDateFormat)
                                                                // where theNewDateFormat is something like 'yyyy/MM/dd' or whatever
                                                                daepConfig.date.format = theNewDateFormat;

                                                                ;


                                                                It should be noted that this solution will not live re-format your md-datepicker's display values. It will only work when the model changes values.






                                                                share|improve this answer













                                                                I'd like to provide my solution that's 100% based off of Christiaan Westerbeek's post. I really like what he did, but I personally wanted something a bit more simplistic.



                                                                appConfig.js



                                                                // config params in global scope that need to be set outside of Angular (due to Angular limitiations)
                                                                var appConfig =
                                                                // enables the dynamic setting of md-datepicker display masks (eg. when user changes language from English to Spanish)
                                                                date:
                                                                // default mask
                                                                format: "MM/dd/yyyy",

                                                                // md-datepicker display format
                                                                mdFormatDate: function (date)
                                                                if (date && date instanceof Date)
                                                                return date.format(appConfig.date.format);

                                                                else
                                                                return null;







                                                                ;


                                                                app.material.config.js



                                                                // set angular material config
                                                                app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider)
                                                                // this is a global object set inside appConfig.js
                                                                $mdDateLocaleProvider.formatDate = appConfig.date.mdFormatDate;

                                                                ]);


                                                                some service file that deals with localization/translations/etc



                                                                // inside the service where you'd track the language/locale change
                                                                service._updateConfigDateFormat = function (theNewDateFormat)
                                                                // where theNewDateFormat is something like 'yyyy/MM/dd' or whatever
                                                                daepConfig.date.format = theNewDateFormat;

                                                                ;


                                                                It should be noted that this solution will not live re-format your md-datepicker's display values. It will only work when the model changes values.







                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered Jul 27 '17 at 17:25









                                                                jc_jc_

                                                                3816




                                                                3816





















                                                                    1














                                                                    For angular-material >= 5.x.x



                                                                    The recommended way of using other custom/predefined date formats is described in the angular material documentation:



                                                                    https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings



                                                                    An implementation example using MomentJS for customizing and parsing datetime display formats:



                                                                    ...
                                                                    import MomentModule from 'angular2-moment';

                                                                    import MatMomentDateModule, MomentDateAdapter, MAT_MOMENT_DATE_FORMATS from '@angular/material-moment-adapter';
                                                                    import DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE from '@angular/material/core';

                                                                    ...

                                                                    // moment formats explanation: https://momentjs.com/docs/#/displaying/format/
                                                                    export const MY_FORMATS =
                                                                    parse:
                                                                    dateInput: 'YYYY-MM-DD',
                                                                    ,
                                                                    display:
                                                                    dateInput: 'YYYY-MM-DD',
                                                                    monthYearLabel: 'MMM YYYY',
                                                                    dateA11yLabel: 'YYYY-MM-DD',
                                                                    monthYearA11yLabel: 'MMMM YYYY',
                                                                    ,
                                                                    ;

                                                                    ...

                                                                    @Component(
                                                                    ...
                                                                    providers: [
                                                                    // `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
                                                                    // `MatMomentDateModule` in your applications root module. We provide it at the component level
                                                                    // here, due to limitations of our example generation script.
                                                                    provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE],
                                                                    // provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS,
                                                                    provide: MAT_DATE_FORMATS, useValue: MY_FORMATS
                                                                    ]
                                                                    )

                                                                    ...


                                                                    Depending on your implementation, inside the component you might also need to use:



                                                                    date = new FormControl(moment());



                                                                    You must also install Moment library and adapter for Angular:



                                                                    https://www.npmjs.com/package/angular2-moment



                                                                    npm install --save angular2-moment



                                                                    https://www.npmjs.com/package/@angular/material-moment-adapter



                                                                    npm install --save @angular/material-moment-adapter






                                                                    share|improve this answer



























                                                                      1














                                                                      For angular-material >= 5.x.x



                                                                      The recommended way of using other custom/predefined date formats is described in the angular material documentation:



                                                                      https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings



                                                                      An implementation example using MomentJS for customizing and parsing datetime display formats:



                                                                      ...
                                                                      import MomentModule from 'angular2-moment';

                                                                      import MatMomentDateModule, MomentDateAdapter, MAT_MOMENT_DATE_FORMATS from '@angular/material-moment-adapter';
                                                                      import DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE from '@angular/material/core';

                                                                      ...

                                                                      // moment formats explanation: https://momentjs.com/docs/#/displaying/format/
                                                                      export const MY_FORMATS =
                                                                      parse:
                                                                      dateInput: 'YYYY-MM-DD',
                                                                      ,
                                                                      display:
                                                                      dateInput: 'YYYY-MM-DD',
                                                                      monthYearLabel: 'MMM YYYY',
                                                                      dateA11yLabel: 'YYYY-MM-DD',
                                                                      monthYearA11yLabel: 'MMMM YYYY',
                                                                      ,
                                                                      ;

                                                                      ...

                                                                      @Component(
                                                                      ...
                                                                      providers: [
                                                                      // `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
                                                                      // `MatMomentDateModule` in your applications root module. We provide it at the component level
                                                                      // here, due to limitations of our example generation script.
                                                                      provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE],
                                                                      // provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS,
                                                                      provide: MAT_DATE_FORMATS, useValue: MY_FORMATS
                                                                      ]
                                                                      )

                                                                      ...


                                                                      Depending on your implementation, inside the component you might also need to use:



                                                                      date = new FormControl(moment());



                                                                      You must also install Moment library and adapter for Angular:



                                                                      https://www.npmjs.com/package/angular2-moment



                                                                      npm install --save angular2-moment



                                                                      https://www.npmjs.com/package/@angular/material-moment-adapter



                                                                      npm install --save @angular/material-moment-adapter






                                                                      share|improve this answer

























                                                                        1












                                                                        1








                                                                        1







                                                                        For angular-material >= 5.x.x



                                                                        The recommended way of using other custom/predefined date formats is described in the angular material documentation:



                                                                        https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings



                                                                        An implementation example using MomentJS for customizing and parsing datetime display formats:



                                                                        ...
                                                                        import MomentModule from 'angular2-moment';

                                                                        import MatMomentDateModule, MomentDateAdapter, MAT_MOMENT_DATE_FORMATS from '@angular/material-moment-adapter';
                                                                        import DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE from '@angular/material/core';

                                                                        ...

                                                                        // moment formats explanation: https://momentjs.com/docs/#/displaying/format/
                                                                        export const MY_FORMATS =
                                                                        parse:
                                                                        dateInput: 'YYYY-MM-DD',
                                                                        ,
                                                                        display:
                                                                        dateInput: 'YYYY-MM-DD',
                                                                        monthYearLabel: 'MMM YYYY',
                                                                        dateA11yLabel: 'YYYY-MM-DD',
                                                                        monthYearA11yLabel: 'MMMM YYYY',
                                                                        ,
                                                                        ;

                                                                        ...

                                                                        @Component(
                                                                        ...
                                                                        providers: [
                                                                        // `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
                                                                        // `MatMomentDateModule` in your applications root module. We provide it at the component level
                                                                        // here, due to limitations of our example generation script.
                                                                        provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE],
                                                                        // provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS,
                                                                        provide: MAT_DATE_FORMATS, useValue: MY_FORMATS
                                                                        ]
                                                                        )

                                                                        ...


                                                                        Depending on your implementation, inside the component you might also need to use:



                                                                        date = new FormControl(moment());



                                                                        You must also install Moment library and adapter for Angular:



                                                                        https://www.npmjs.com/package/angular2-moment



                                                                        npm install --save angular2-moment



                                                                        https://www.npmjs.com/package/@angular/material-moment-adapter



                                                                        npm install --save @angular/material-moment-adapter






                                                                        share|improve this answer













                                                                        For angular-material >= 5.x.x



                                                                        The recommended way of using other custom/predefined date formats is described in the angular material documentation:



                                                                        https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings



                                                                        An implementation example using MomentJS for customizing and parsing datetime display formats:



                                                                        ...
                                                                        import MomentModule from 'angular2-moment';

                                                                        import MatMomentDateModule, MomentDateAdapter, MAT_MOMENT_DATE_FORMATS from '@angular/material-moment-adapter';
                                                                        import DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE from '@angular/material/core';

                                                                        ...

                                                                        // moment formats explanation: https://momentjs.com/docs/#/displaying/format/
                                                                        export const MY_FORMATS =
                                                                        parse:
                                                                        dateInput: 'YYYY-MM-DD',
                                                                        ,
                                                                        display:
                                                                        dateInput: 'YYYY-MM-DD',
                                                                        monthYearLabel: 'MMM YYYY',
                                                                        dateA11yLabel: 'YYYY-MM-DD',
                                                                        monthYearA11yLabel: 'MMMM YYYY',
                                                                        ,
                                                                        ;

                                                                        ...

                                                                        @Component(
                                                                        ...
                                                                        providers: [
                                                                        // `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
                                                                        // `MatMomentDateModule` in your applications root module. We provide it at the component level
                                                                        // here, due to limitations of our example generation script.
                                                                        provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE],
                                                                        // provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS,
                                                                        provide: MAT_DATE_FORMATS, useValue: MY_FORMATS
                                                                        ]
                                                                        )

                                                                        ...


                                                                        Depending on your implementation, inside the component you might also need to use:



                                                                        date = new FormControl(moment());



                                                                        You must also install Moment library and adapter for Angular:



                                                                        https://www.npmjs.com/package/angular2-moment



                                                                        npm install --save angular2-moment



                                                                        https://www.npmjs.com/package/@angular/material-moment-adapter



                                                                        npm install --save @angular/material-moment-adapter







                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Mar 26 '18 at 10:47









                                                                        Alex PandreaAlex Pandrea

                                                                        447718




                                                                        447718





















                                                                            0














                                                                            If you are using the latest version of angular-material.js then use the $mdDateLocale service. This code sample uses angular's built in date filter as an alternative to using the moment.js library. See other date format options using angular's $filter service here at this link https://docs.angularjs.org/api/ng/filter/date.



                                                                            // mainController.js
                                                                            angular.module('app').config(function($mdDateLocale, $filter, $scope)

                                                                            // FORMAT THE DATE FOR THE DATEPICKER
                                                                            $mdDateLocale.formatDate = function(date)
                                                                            return $filter('date')($scope.myDate, "mediumDate");
                                                                            ;

                                                                            );





                                                                            share|improve this answer



























                                                                              0














                                                                              If you are using the latest version of angular-material.js then use the $mdDateLocale service. This code sample uses angular's built in date filter as an alternative to using the moment.js library. See other date format options using angular's $filter service here at this link https://docs.angularjs.org/api/ng/filter/date.



                                                                              // mainController.js
                                                                              angular.module('app').config(function($mdDateLocale, $filter, $scope)

                                                                              // FORMAT THE DATE FOR THE DATEPICKER
                                                                              $mdDateLocale.formatDate = function(date)
                                                                              return $filter('date')($scope.myDate, "mediumDate");
                                                                              ;

                                                                              );





                                                                              share|improve this answer

























                                                                                0












                                                                                0








                                                                                0







                                                                                If you are using the latest version of angular-material.js then use the $mdDateLocale service. This code sample uses angular's built in date filter as an alternative to using the moment.js library. See other date format options using angular's $filter service here at this link https://docs.angularjs.org/api/ng/filter/date.



                                                                                // mainController.js
                                                                                angular.module('app').config(function($mdDateLocale, $filter, $scope)

                                                                                // FORMAT THE DATE FOR THE DATEPICKER
                                                                                $mdDateLocale.formatDate = function(date)
                                                                                return $filter('date')($scope.myDate, "mediumDate");
                                                                                ;

                                                                                );





                                                                                share|improve this answer













                                                                                If you are using the latest version of angular-material.js then use the $mdDateLocale service. This code sample uses angular's built in date filter as an alternative to using the moment.js library. See other date format options using angular's $filter service here at this link https://docs.angularjs.org/api/ng/filter/date.



                                                                                // mainController.js
                                                                                angular.module('app').config(function($mdDateLocale, $filter, $scope)

                                                                                // FORMAT THE DATE FOR THE DATEPICKER
                                                                                $mdDateLocale.formatDate = function(date)
                                                                                return $filter('date')($scope.myDate, "mediumDate");
                                                                                ;

                                                                                );






                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Apr 12 '17 at 20:12









                                                                                Ian Poston FramerIan Poston Framer

                                                                                36848




                                                                                36848





















                                                                                    0














                                                                                    I used $mdDateLocaleProvider to format it on the frond end. If you want to format date while sending it to the back end, the following worked for me :-



                                                                                    $filter('date')(this.date, 'MM/dd/yyyy');


                                                                                    I have the above in controller.






                                                                                    share|improve this answer





























                                                                                      0














                                                                                      I used $mdDateLocaleProvider to format it on the frond end. If you want to format date while sending it to the back end, the following worked for me :-



                                                                                      $filter('date')(this.date, 'MM/dd/yyyy');


                                                                                      I have the above in controller.






                                                                                      share|improve this answer



























                                                                                        0












                                                                                        0








                                                                                        0







                                                                                        I used $mdDateLocaleProvider to format it on the frond end. If you want to format date while sending it to the back end, the following worked for me :-



                                                                                        $filter('date')(this.date, 'MM/dd/yyyy');


                                                                                        I have the above in controller.






                                                                                        share|improve this answer















                                                                                        I used $mdDateLocaleProvider to format it on the frond end. If you want to format date while sending it to the back end, the following worked for me :-



                                                                                        $filter('date')(this.date, 'MM/dd/yyyy');


                                                                                        I have the above in controller.







                                                                                        share|improve this answer














                                                                                        share|improve this answer



                                                                                        share|improve this answer








                                                                                        edited Aug 24 '17 at 15:34









                                                                                        Jason Roman

                                                                                        6,394102730




                                                                                        6,394102730










                                                                                        answered Aug 24 '17 at 15:24









                                                                                        java devjava dev

                                                                                        11




                                                                                        11





















                                                                                            0














                                                                                            in my case I was loosing the PlaceHolder everythig works but the placeHolder was disappearing when I use custom formatting. Below lines solved my problem with placeholder.



                                                                                            $mdDateLocaleProvider.formatDate = function (date) 
                                                                                            if(date==null)
                                                                                            return "";
                                                                                            var m = moment(date);
                                                                                            return m.isValid() ? m.format('L') : '';
                                                                                            ;





                                                                                            share|improve this answer



























                                                                                              0














                                                                                              in my case I was loosing the PlaceHolder everythig works but the placeHolder was disappearing when I use custom formatting. Below lines solved my problem with placeholder.



                                                                                              $mdDateLocaleProvider.formatDate = function (date) 
                                                                                              if(date==null)
                                                                                              return "";
                                                                                              var m = moment(date);
                                                                                              return m.isValid() ? m.format('L') : '';
                                                                                              ;





                                                                                              share|improve this answer

























                                                                                                0












                                                                                                0








                                                                                                0







                                                                                                in my case I was loosing the PlaceHolder everythig works but the placeHolder was disappearing when I use custom formatting. Below lines solved my problem with placeholder.



                                                                                                $mdDateLocaleProvider.formatDate = function (date) 
                                                                                                if(date==null)
                                                                                                return "";
                                                                                                var m = moment(date);
                                                                                                return m.isValid() ? m.format('L') : '';
                                                                                                ;





                                                                                                share|improve this answer













                                                                                                in my case I was loosing the PlaceHolder everythig works but the placeHolder was disappearing when I use custom formatting. Below lines solved my problem with placeholder.



                                                                                                $mdDateLocaleProvider.formatDate = function (date) 
                                                                                                if(date==null)
                                                                                                return "";
                                                                                                var m = moment(date);
                                                                                                return m.isValid() ? m.format('L') : '';
                                                                                                ;






                                                                                                share|improve this answer












                                                                                                share|improve this answer



                                                                                                share|improve this answer










                                                                                                answered Mar 22 at 11:03









                                                                                                katmancokatmanco

                                                                                                9751023




                                                                                                9751023



























                                                                                                    draft saved

                                                                                                    draft discarded
















































                                                                                                    Thanks for contributing an answer to Stack Overflow!


                                                                                                    • Please be sure to answer the question. Provide details and share your research!

                                                                                                    But avoid


                                                                                                    • Asking for help, clarification, or responding to other answers.

                                                                                                    • Making statements based on opinion; back them up with references or personal experience.

                                                                                                    To learn more, see our tips on writing great answers.




                                                                                                    draft saved


                                                                                                    draft discarded














                                                                                                    StackExchange.ready(
                                                                                                    function ()
                                                                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32566416%2fchange-format-of-md-datepicker-in-angular-material-with-momentjs%23new-answer', 'question_page');

                                                                                                    );

                                                                                                    Post as a guest















                                                                                                    Required, but never shown





















































                                                                                                    Required, but never shown














                                                                                                    Required, but never shown












                                                                                                    Required, but never shown







                                                                                                    Required, but never shown

































                                                                                                    Required, but never shown














                                                                                                    Required, but never shown












                                                                                                    Required, but never shown







                                                                                                    Required, but never shown







                                                                                                    Popular posts from this blog

                                                                                                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                                                                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                                                                                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript