0
votes

I am using angular material (md-datepicker). My requirement is to set different date format based on selection. i.e. if user select 'daily', datepicker would show 'MM/DD/YYYY'. If user select 'monthly' then datepicker should show 'MMM YYYY' and for 'hourly', it should be 'MM/DD/YYYY hh:mm'

https://plnkr.co/edit/S4mnF7?p=preview

Is it feasible using md-datepicker? I do not see any option to set format property in HTML. Saw the documentation of $mdDateLocaleProvider. But it does not give option to set different format to different controls.

1

1 Answers

3
votes

You can use $mdDateLocaleProvider , the formatDate function to set the date format: Function to format a date object to a string. The datepicker directive also provides the time zone, if it was specified.

And in the datepicker directive, you can use the md-date-locale attribute: This Allows for the values from the $mdDateLocaleProvider to be ovewritten on a per-element basis (e.g. msgOpenCalendar can be overwritten with md-date-locale="{ msgOpenCalendar: 'Open a special calendar' }").

something like:

<md-datepicker ng-model="myDate"  md-date-locale="mylocale"></md-datepicker>
<md-datepicker ng-model="myOtherDate"  md-date-locale="myOtherlocale"></md-datepicker>

and in controller

$scope.mylocale = {
  formatDate: function(date) {
    var m = moment(date);
    return m.isValid() ? m.format('YYYY') : '';
  }
};
$scope.myOtherlocale = {
  formatDate: function(date) {
    var m = moment(date);
    return m.isValid() ? m.format('MMMM YYYY') : '';
  }
};

https://embed.plnkr.co/u9wY3rvtpmXdQ7zrbMpB/