Last active
December 19, 2019 08:33
-
-
Save Gkemon/72d9c41eee5850e990ade4947d9ac259 to your computer and use it in GitHub Desktop.
This gist is for conversion of unix to human readable time like "Just now", " 2 days ago" , " 6 hours later" etc.
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 class unixToHuman { | |
private static final int SECOND_MILLIS = 1000; | |
private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS; | |
private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS; | |
private static final int DAY_MILLIS = 24 * HOUR_MILLIS; | |
private static final int WEEK_MILLIS = 7 * DAY_MILLIS ; | |
public static String getTimeAgo(long time) { | |
if (time < 1000000000000L) { | |
// if timestamp given in seconds, convert to millis | |
time *= 1000; | |
} | |
long now =System.currentTimeMillis();; | |
long diff = now - time; | |
if(diff>0) { | |
if (diff < MINUTE_MILLIS) { | |
return "just now"; | |
} else if (diff < 2 * MINUTE_MILLIS) { | |
return "a minute ago"; | |
} else if (diff < 50 * MINUTE_MILLIS) { | |
return diff / MINUTE_MILLIS + " minutes ago"; | |
} else if (diff < 90 * MINUTE_MILLIS) { | |
return "an hour ago"; | |
} else if (diff < 24 * HOUR_MILLIS) { | |
return diff / HOUR_MILLIS + " hours ago"; | |
} else if (diff < 48 * HOUR_MILLIS) { | |
return "yesterday"; | |
} else if (diff < 7 * DAY_MILLIS) { | |
return diff / DAY_MILLIS + " days ago"; | |
} else if (diff < 2 * WEEK_MILLIS) { | |
return "a week ago"; | |
} else if (diff < WEEK_MILLIS * 3) { | |
return diff / WEEK_MILLIS + " weeks ago"; | |
} else { | |
java.util.Date date = new java.util.Date((long) time); | |
return date.toString(); | |
} | |
} | |
else { | |
diff=time-now; | |
if (diff < MINUTE_MILLIS) { | |
return "this minute"; | |
} else if (diff < 2 * MINUTE_MILLIS) { | |
return "a minute later"; | |
} else if (diff < 50 * MINUTE_MILLIS) { | |
return diff / MINUTE_MILLIS + " minutes later"; | |
} else if (diff < 90 * MINUTE_MILLIS) { | |
return "an hour later"; | |
} else if (diff < 24 * HOUR_MILLIS) { | |
return diff / HOUR_MILLIS + " hours later"; | |
} else if (diff < 48 * HOUR_MILLIS) { | |
return "tomorrow"; | |
} else if (diff < 7 * DAY_MILLIS) { | |
return diff / DAY_MILLIS + " days later"; | |
} else if (diff < 2 * WEEK_MILLIS) { | |
return "a week later"; | |
} else if (diff < WEEK_MILLIS * 3) { | |
return diff / WEEK_MILLIS + " weeks later"; | |
} else { | |
java.util.Date date = new java.util.Date((long) time); | |
return date.toString(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment