2
votes

How to format model variable of md-datepicker in particular format. I tried config of $mdDateLocaleProvider, But it just formatted the display value of date-picker, not the model value. Please look at this codepen or below code:

HTML:

<div ng-app="MyApp" ng-controller="AppCtrl">
  <md-content>
    <md-datepicker ng-model="myDate" md-placeholder="Enter date"></md-datepicker>
  </md-content>
  <p>Date not formatted:</p>
  {{myDate}}
</div>

JS:

angular.module('MyApp')
    .controller('AppCtrl', function($scope) {
      $scope.myDate = new Date();
    })

.config(function($mdDateLocaleProvider) {
  $mdDateLocaleProvider.formatDate = function(date) {
    return moment(date).format('YYYY-MM-DD');
  };
});
3

3 Answers

1
votes

You should use the angular 'date' filter

{{myDate | date:'yyyy-MM-dd'}}

For more formatting and other info see: https://docs.angularjs.org/api/ng/filter/date

0
votes
var dateFormat = function(date) {

    var date = date.getDate();
    var month = date.getMonth();
    var year = date.getFullYear();
    var formattedDate = (date < 10 ?  ('0' + date) : date) + '/' + (month < 10 ?  ('0' + month) : month) + '/' + year;
}

Or

return date.getDate() + "/" +date.getMonth()+1 + "/" + date.getFullYear();

Will give your 01/08/2016. (You need to +1 getMonth() because January is 0). Is this what you are looking for?

Edit: function

0
votes

The model object is always a javascript date object, you can only change the representation when you render it (for example with moment as you do, or the already mentioned angular date filter).

Maybe you should read up on date formats in javascript and in JSON: The “right” JSON date format

You can however transform the date object before you send it to your server/backend. If you use REST with $resource or $http you can use something like angular-http-transform-date or do it on your own by adding a request transformer to the $httpProvider. There is a blog post which shows how to do it for responses, but the same mechanism applies for requests.