2

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');
  };
});
Saurabh
  • 71,488
  • 40
  • 181
  • 244

3 Answers3

1

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

Ron Brogan
  • 892
  • 1
  • 9
  • 25
  • Well, actually I dont want to show it in the UI, I want to send it to a backend system, so if I can directly get it from some format related config/option. – Saurabh Jan 08 '16 at 17:15
  • As far as I can tell, the problem you're having is that the model supplied by the date picker is a `Date` object, not a string that is formatted. You could format that date into a string using various methods and do what you need to it. If necessary, `watch()` the model and format it into a new object. – Ron Brogan Jan 08 '16 at 17:17
0
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

D.Jacobi
  • 29
  • 5
0

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.

Community
  • 1
  • 1
kuhnroyal
  • 7,188
  • 1
  • 34
  • 47