How to get a formatted string from an object of type Date
in format dd/MM/yyyy
?
How to get a formatted string from an object of type Date
in format dd/MM/yyyy
?
To format Angular dates, there is Angular Filter that is very useful and easy to use , either in view
or controllers
. filter
can still be used to format any type of object. For date there are several possible combinations.
{{ filter_expression | filter : expression : comparator}}
$filter('filter')(array, expression, comparator)
You can convert your Date object to any string
based on settings, here are some examples:
yyyy
year with 4 digits MM
month with 2 digits (01-12) M
month with 1 or 2 digits (1-12) dd
day with two digits (01-31) d
day with 1 or 2 digits (1-31) You can also add Angular Locale in your project to use the formats in the language you want, in our case PT-BR or PT-PT .
angular
.module('myApp', [])
.controller('myController', myController);
myController.$inject = ['$scope'];
function myController($scope) {
$scope.data = new Date(2014, 11 - 1, 13, 17, 17, 47, 0);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp" ng-controller="myController">
<p><b>Valor original:</b> {{ data }}</p>
<p><b>dd/MM/yyyy:</b> {{ data | date: 'dd/MM/yyyy' }}</p>
<p><b>Data completa:</b> {{ data | date: 'fullDate' }}</p>
</div>
angular
.module('myApp', [])
.controller('myController', myController);
myController.$inject = ['$scope', '$filter'];
function myController($scope, $filter) {
var data = new Date(2014, 11 - 1, 13, 17, 17, 47, 0);
$scope.data = data;
$scope.dataFormatada = $filter('date')(data, 'dd/MM/yyyy');
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp" ng-controller="myController">
<p><b>Original:</b> {{ data }}</p>
<p><b>Formatada:</b> {{ dataFormatada }}</p>
</div>
@Pedro's answer already answers your question, but I'd like to show an example where we can work with direct filters in Controller
:
var myApp = angular.module('myApp',[]);
myApp.controller("MyCtrl", function($scope, $filter){
var data = "2016-02-18T10:23Z";
$scope.dataFormatada = $filter('date')(data, 'dd/MM/yyyy');
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp" ng-controller="MyCtrl">
Data Formatada, {{dataFormatada}}!
</div>
NOTE: To work with dates in our format I recommend taking a look at locale
This filter helps me deal with timestamps
dateFilter.js
angular.module("zendapp").filter("brdateFilter", function(){
return function(input) {
var o = input.replace(/-/g, "/"); // Troca hifen por barra
return Date.parse(o + " -0000");
};
});
index.html
{{row.created_at.date | brdateFilter | date:"dd/MM/yyyy HH:mm"}}