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.
}
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 = timeDiff / 24; // in days
if(timeDiff <= 7){
timeDiffStr = timeDiff + " days ago";
return timeDiffStr;
}
timeDiff = timeDiff / 7;
if(timeDiff <= 4){
timeDiffStr = timeDiff + " weeks ago";
return timeDiffStr;
}
timeDiff = timeDiff / 4;
timeDiffStr = timeDiff + " months ago";
return timeDiffStr;
Comments
Post a Comment