Posts

Showing posts from January, 2015

Getting time diff from timestamp in Java

You have a timestamp and you want to get the difference in string like the folowing: 10 sec ago 3 minute ago 7 days ago  and so on. The following function does it. private String getTimeDiff( long timestamp){     String timeDiffStr = "" ;       Calendar cal = Calendar.getInstance();       long currentTimeInMillis = cal.getTimeInMillis();       long timeDiff = (currentTimeInMillis - timestamp) / 1000;       if (timeDiff < 60){             timeDiffStr = timeDiff + " seconds ago" ;             return timeDiffStr;       }       timeDiff = timeDiff / 60;       if (timeDiff < 60){             timeDiffStr = timeDiff + " minutes ago" ;             return timeDiffStr;       }       timeDiff = timeDiff / 60; // in hours       if (timeDiff < 24){             timeDiffStr = timeDiff + " hours ago" ;             return timeDiffStr;       }       timeDiff = timeD