How do I convert a date into the American format in Angular?

7

I am using a Json answer in Laravel 5, where I use the Angular to be able to display this data.

The date in Laravel is returned in 2017-05-17 15:56:46 format. When attempting to use the date filter on the angle, the same thing continued:

angular.module('app', []);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="app">
 {{ '2017-05-17 15:56:46' | date: 'dd/MM/yyyy' }}
</div>

In case of dates in the above format, how should I do to be able to convert to dd/MM/yyyy format?

    
asked by anonymous 18.05.2017 / 14:35

2 answers

7

What you put in view is string and not a date. The date filter can only be applied to objects of type date .

angular.module('app', []);

angular.module('app').controller('mainController', mainCtrlFn);

function mainCtrlFn() {
    this.data = new Date();
    this.dataLaravel = new Date('2017-05-17 15:56:46');
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="app" ng-controller="mainController as mainCtrl">
 {{ mainCtrl.data | date: 'dd/MM/yyyy' }} <br>
 {{ mainCtrl.dataLaravel | date: 'dd/MM/yyyy' }}
</div>
    
18.05.2017 / 14:42
3

As discussed in the comments, and also as an alternative answer, we can use a module to improve working with dates in AngularJS.

It would be the Angular-Moment module.

It has several benefits, such as:

  • Set locale for dates
  • Choose the view through filter (similar to jbueno's response) {{ date | amDateFormat:'MM.DD.YYYY HH:mm:ss' }}
  • Define difference in UTC, etc. {{ date | amUtcOffset:'+0300' }}
  • Create time messages already passed, eg "17 min ago" {{ <span am-time-ago="date | amParse:'YYYY.MM.DD HH:mm:ss'"></span> }}

Among other great features!

Of course, it will depend on the need and scope of the project, but it is a good alternative.

    
18.05.2017 / 15:48