Created
June 28, 2011 07:54
-
-
Save karlili/1050689 to your computer and use it in GitHub Desktop.
Implementation of a human readable date display
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
/** | |
* An implementation on getting the human readable date format from milliseconds | |
* which is commonly used in Facebook, like about x hours ago. | |
* Convention as follows: | |
* 1000 milliseconds = 1 second, | |
* 60 seconds = 1 minute, | |
* 60 minutes = 1 hour, | |
* 24 hours = 1 day, | |
* 12 days = 1 month, | |
* 12 month = 1 year. | |
*/ | |
private static String getHumanReadableDateDisplay(long pastMillisecond){ | |
Calendar cal = Calendar.getInstance(); | |
long currentMillisecond = cal.getTimeInMillis(); | |
long diff = currentMillisecond - pastMillisecond; | |
int[] units = new int[] {1000,60,60,24,30,12}; | |
String[] unitName = new String[] {"seconds", "minutes", "hours", "days", "months", "years"}; | |
double f = diff; | |
int bound = 1; | |
int i = 0; | |
int j = 0; | |
long roundedValue = 0; | |
while (bound <= 1 && i < units.length){ | |
f = f/units[i]; | |
bound = Double.compare(f, 1); | |
roundedValue = Math.round(f); | |
if (roundedValue <= 1){ | |
roundedValue = Math.round(f * units[i]); | |
return "about "+ roundedValue + " "+unitName[j-1]+ " ago"; | |
}else{ | |
//System.out.println(i+"("+f+"/"+units[i]+") : about "+ roundedValue + " "+unitName[j]); | |
i++; | |
j++; | |
} | |
}//end of while | |
return "about "+ roundedValue + " "+unitName[j-1]+ "ago"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment