Last active
December 4, 2016 17:08
-
-
Save peterdresslar/84fbba0afefa289e0d6a84659ae6ea9c to your computer and use it in GitHub Desktop.
Java readable time ago
This file contains 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 getAgoString(Date occurrence) { | |
try { | |
Date now = new Date(); | |
long duration = now.getTime() - occurrence.getTime(); | |
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration); | |
long hours = TimeUnit.MILLISECONDS.toHours(duration); | |
long days = TimeUnit.MILLISECONDS.toDays(duration); | |
if (days > 180) { | |
return " billions and billions of years ago"; | |
} | |
if (days > 0) { | |
return (days == 1) ? days + " day ago" : days + " days ago"; | |
} | |
if (hours > 0) { | |
return (hours == 1) ? hours + " hour ago" : hours + " hours ago"; | |
} | |
if (minutes > 0) { | |
return (minutes == 1) ? minutes + " minute ago" : minutes + " minutes ago"; | |
} | |
} catch (Exception e) { | |
return "At some point in the past, presumably"; //TODO fieldtest accuracy of assertion | |
} | |
return "Just now"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment