Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to calculate time difference in Android?




public static String getDateDifference(Date thenDate){
Calendar now = Calendar.getInstance();
Calendar then = Calendar.getInstance();
now.setTime(new Date());
then.setTime(thenDate);


// Get the represented date in milliseconds
long nowMs = now.getTimeInMillis();
long thenMs = then.getTimeInMillis();

// Calculate difference in milliseconds
long diff = nowMs - thenMs;

// Calculate difference in seconds
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);

if (diffMinutes<60){
if (diffMinutes==1)
return diffMinutes + " minute ago";
else
return diffMinutes + " minutes ago";
} else if (diffHours<24){
if (diffHours==1)
return diffHours + " hour ago";
else
return diffHours + " hours ago";
}else if (diffDays<30){
if (diffDays==1)
return diffDays + " day ago";
else
return diffDays + " days ago";
}else {
return "a long time ago..";
}
}
}






This post first appeared on Android Training In Kerala, please read the originial post: here

Share the post

How to calculate time difference in Android?

×

Subscribe to Android Training In Kerala

Get updates delivered right to your inbox!

Thank you for your subscription

×