AngularJS Date Filter Example
by i_woody
HTML
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<div ng-app="MyTimeAgoModule" ng-controller="Ctrl">
<div class="container-fluid">
<div class='well'><h1>Time-ago Filter Example</h1></div>
You loaded this example
<span>{{loadtime|timeago}}</span>.
The original Fiddle was created <span>{{fiddletime|timeago}}</span>.
</div>
<div class="container-fluid">
<label for="time-input">Live Example to filter: <input name="time-input" ng-model="timestamp" type="timestamp"></label>
<dl>
<dt>No filter:</dt><dd>{{timestamp}}</dd>
<dt>TimeAgo:</dt><dd>{{timestamp|timeago}}</dd>
<dt>TimeAgo Allow future:</dt><dd>{{timestamp|timeago:true}}</dd>
</div>
</div>
<p>Note: this example doesn't do live updating - just a proof of concept</p>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<style>
.ng-invalid { border: 1px solid red; }
body {
margin: 20px;
}
span {
color: gray;
text-decoration: underline;
}
.container-fluid {
margin-bottom: 2em;
}
JavaScript
angular.module('MyTimeAgoModule', []).
filter('timeago', function() {
return function(input, p_allowFuture) {
var substitute = function (stringOrFunction, number, strings) {
var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, dateDifference) : stringOrFunction;
var value = (strings.numbers && strings.numbers[number]) || number;
return string.replace(/%d/i, value);
},
nowTime = (new Date()).getTime(),
date = (new Date(input)).getTime(),
//refreshMillis= 6e4, //A minute
allowFuture = p_allowFuture || false,
strings= {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "ago",
suffixFromNow: "from now",
seconds: "less than a minute",
minute: "about a minute",
minutes: "%d minutes",
hour: "about an hour",
hours: "about %d hours",
day: "a day",
days: "%d days",
month: "about a month",
months: "%d months",
year: "about a year",
years: "%d years"
},
dateDifference = nowTime - date,
words,
seconds = Math.abs(dateDifference) / 1000,
minutes = seconds / 60,
hours = minutes / 60,
days = hours / 24,
years = days / 365,
separator = strings.wordSeparator === undefined ? " " : strings.wordSeparator,
// var strings = this.settings.strings;
prefix = strings.prefixAgo,
suffix = strings.suffixAgo;
if (allowFuture) {
if (dateDifference < 0) {
...