If you have UNIX time-stamps and you want convert it to show how may seconds, minutes, hours, weeks, months, years or decades ago it is from now you may use the following snippet of code. It accepts UNIX time-stamp in long format, In case you are getting UNIX time-stamps in String format you have to convert it to long. It will return a string with either seconds, minutes , hours , days, weeks, months, years , or decades ago. The code is written in java for an android app but can be ported to any language. Here is the code which is also available on github.
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
public static String caluculateTimeAgo(long timeStamp) { | |
long timeDiffernce; | |
long unixTime = System.currentTimeMillis() / 1000L; //get current time in seconds. | |
int j; | |
String[] periods = {"s", "m", "h", "d", "w", "m", "y", "d"}; | |
// you may choose to write full time intervals like seconds, minutes, days and so on | |
double[] lengths = {60, 60, 24, 7, 4.35, 12, 10}; | |
timeDiffernce = unixTime – timeStamp; | |
String tense = "ago"; | |
for (j = 0; timeDiffernce >= lengths[j] && j < lengths.length – 1; j++) { | |
timeDiffernce /= lengths[j]; | |
} | |
return timeDiffernce + periods[j] + " " + tense; | |
} |