Last active
May 9, 2019 09:07
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was missing it , will fix