Change format of md-datepicker in Angular Material with momentjs

前端 未结 13 720
再見小時候
再見小時候 2020-11-28 09:01

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 su

相关标签:
13条回答
  • 2020-11-28 09:30

    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

    0 讨论(0)
  • 2020-11-28 09:32

    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);
    };
    
    0 讨论(0)
  • 2020-11-28 09:32

    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') : '';
                };
    
    0 讨论(0)
  • 2020-11-28 09:35

    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;
    
      };
    });
    
    0 讨论(0)
  • 2020-11-28 09:39

    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.

    0 讨论(0)
  • 2020-11-28 09:42

    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.

    0 讨论(0)
提交回复
热议问题