Search code examples
angularjsangular-formlyangular-ui-datepicker

How to change Angular UI Datepicker model value format in angular formly?


Here is the default format of UI Datepicker of angular formly

  {
    "date": "2015-10-05T18:30:00.000Z"
  }

How to change the above format into

  {
    "date": "2015/10/05"
  }

Here is the JSBIN: http://jsbin.com/cadaga/2/edit?html,js,output


Solution

  • Usually, in the model you store the date in ISO format like you already have, and you format it in the view as you wish, using the date filter (documentation):

    <div>{{vm.model.date | date: 'yyyy/MM/dd'}}</div>
    

    If you anyway want to change the format in the model, inject $filter and use date filter like the following:

    $filter('date')(date_value, format, timezone)

    e.g:

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

    Alternatively, if you are manipulating dates a lot, a library like moment.js can be useful.


    Edit: Noticed you want to change the date model value in the concrete context of angular-formly with a datepicker component. The component needs the date model value to be in a standard format, but what you can do is to have another property with the corresponding formatted date, that you would set on change of the date input:

    HTML (on the datepicker input):

    ng-change="vm.setFormattedDate(dt)"
    

    Controller:

    vm.setFormattedDate = function (datetime) {
        vm.model.formattedDate = $filter('date')(datetime, 'yyyy/MM/dd');
    }