Skip to content

Instantly share code, notes, and snippets.

@akuafif
Created December 10, 2015 21:02
Show Gist options
  • Save akuafif/e4a02134b4af05923beb to your computer and use it in GitHub Desktop.
Save akuafif/e4a02134b4af05923beb to your computer and use it in GitHub Desktop.
[Java] Smart Display of TimeAgo using miliseconds (eg. 20 days ago)
public static void main(){
// String to convert into date
String toConvert = "2015-12-09 13:48:17"
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Convert the string into date
Date convertedDate = formatter.parse(toConvert);
// Get Current Date
Date now = new Date();
// Get date difference in milliseconds
long diffInMillies = now.getTime() - convertedDate.getTime();
// Return result
System.out.println(TimeAgo.toDuration(diffInMillies));
}
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class TimeAgo {
public static final List<Long> times = Arrays.asList(
TimeUnit.DAYS.toMillis(365),
TimeUnit.DAYS.toMillis(30),
TimeUnit.DAYS.toMillis(1),
TimeUnit.HOURS.toMillis(1),
TimeUnit.MINUTES.toMillis(1),
TimeUnit.SECONDS.toMillis(1));
public static final List<String> timesString = Arrays.asList("year", "month", "day", "hour", "minute", "second");
public static String toDuration(long duration) {
StringBuffer res = new StringBuffer();
for (int i = 0; i < times.size(); i++) {
Long current = times.get(i);
long temp = duration / current;
if (temp > 0) {
res.append(temp).append(" ").append(timesString.get(i)).append(temp > 1 ? "s" : "").append(" ago");
break;
}
}
if ("".equals(res.toString()))
return "0 second ago";
else
return res.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment