Reputation: 571
I want to show human readable date time in my frontend. My data comes from rails backend. When I use {{ item.created_at }}
it shows the time like rails way 2016-10-10T10:29:47.993Z. But How can I show this like 5 days ago, 3 hours ago in angular js?
Upvotes: 1
Views: 1638
Reputation: 4233
To format dates in angular you can use date
filter like this:
{{ item.created_at | date:'yyyy-MM-dd HH:mm' }}
You are looking for a very particular format so I think you need to build a custom filter to show exactly that. You can use this filter scaffolding:
.filter('customDate', function() {
return function(date) {
// 1. Get current date
// 2. Get diff from expression date to current
// 3. Apply your format and return result;
};
});
Lastly there is a library called momentjs to manipulate dates and times and there is an angular version of that:
Check the am-time-ago directive of the library:
<span am-time-ago="item.created_at"></span>
Upvotes: 2
Reputation: 5273
Try this, Create a filter for that, for reusability of code
var jimApp = angular.module("mainApp", []);
jimApp.controller('mainCtrl', function($scope){
$scope.date = "1992-05-07T22:00:00.000Z";
});
jimApp.filter('dateFilter', function() {
function calculateDate(date) {
date = new Date(date);
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
return day+'-'+month+'-'+year;
}
return function(date) {
return calculateDate(date);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
<div>{{date | dateFilter}}</div>
</div>
Upvotes: 1