How to convert a date to American format in Angular?
I'm using a Json response in Laravel 5, where I use Angular to be able to display this data.
The date in Laravel is returned in the format 2017-05-17 15:56:46
. When trying to use the filter date
in angular, it continued to display the same thing:
angular.module('app', []);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
{{ '2017-05-17 15:56:46' | date: 'dd/MM/yyyy' }}
</div>
In cases of dates in the format above, how should I do to be able to convert to the format dd/MM/yyyy
?
2 answers
That you put in View is a string
and not a date. The filter date
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>
<div ng-app="app" ng-controller="mainController as mainCtrl">
{{ mainCtrl.data | date: 'dd/MM/yyyy' }} <br>
{{ mainCtrl.dataLaravel | date: 'dd/MM/yyyy' }}
</div>
As discussed in the comments, and also as an alternative answer, we can use a module to improve the work with dates in AngularJS.
Would be the Module Angular-Moment .
It has several benefits, such as:
- set the locale for dates
- choose Display mode through filter (similar to jbueno's response)
{{ date | amDateFormat:'MM.DD.YYYY HH:mm:ss' }}
- set difference in UTC, etc.
{{ date | amUtcOffset:'+0300' }}
- create time messages already elapsed, e.g. "17 min ago"
{{ <span am-time-ago="date | amParse:'YYYY.MM.DD HH:mm:ss'"></span> }}
Among other great features!
Logical, it will depend on the need and scope of the project, but it is a good alternative.