Skip to content

Instantly share code, notes, and snippets.

@sarathsp06
Last active May 9, 2019 09:07
Show Gist options
  • Save sarathsp06/cdb738c393edad149863 to your computer and use it in GitHub Desktop.
Save sarathsp06/cdb738c393edad149863 to your computer and use it in GitHub Desktop.
Angular filter to convert a time in milliseconds to relative human readable time
(function(){
"use strict":
angular.module('ng-relativeDate',[])
.filter('ngrelativeDate',function(){
/**
* [humanreadableDate converts the timestamp into human readable time ]
* @param {Int} timestamp - time as number of milliseconds since 1970/01/01:
* @return {string} relative time corresponding to timestamp
*/
var humanReadableDate = function (timestamp){
var now = new Date();
var midnightToday = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0).getTime();
var firstOfTheYear = new Date(now.getFullYear(), 0, 1, 0, 0, 0).getTime();
var nowTime = (new Date().getTime());
var timeDiff = (nowTime - timestamp)/1000;
var minsAgo = Math.floor(timeDiff/60);
var hoursAgo = Math.floor(timeDiff/3600);
var text;
if (timeDiff > 0 && timeDiff < 22 *3600) {
if (timeDiff < 60) {
text = 'few seconds ago';
}
else if (timeDiff < 92) {
text = 'a minute ago';
}
else if (timeDiff < 3300) {
text = minsAgo + " mins ago";
}
else if (timeDiff < 5400) {
text = 'an hour ago';
}
else if (timeDiff < 22 * 3600) {
text = 'about ' + hoursAgo + ' hour ago';
}
} else {
var year = parseInt(new Date(timestamp).getFullYear()) <
parseInt(new Date().getFullYear()) ?
new Date(timestamp).getFullYear()+" ,":"";
text = year+convertTimeToString(timestamp, midnightToday, firstOfTheYear);
}
return text;
}
return humanReadableDate;
});
}).call(this);
@biswajitpanday
Copy link

This is cool.. But getting an error..
where is the convertTimeToString() method implementation..?? are you missing it or me...??

@sarathsp06
Copy link
Author

I was missing it , will fix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment