Skip to content

Instantly share code, notes, and snippets.

@vishvendra01
Created September 18, 2015 11:32
Show Gist options
  • Save vishvendra01/0bbd25a38477892bfd64 to your computer and use it in GitHub Desktop.
Save vishvendra01/0bbd25a38477892bfd64 to your computer and use it in GitHub Desktop.
get time difference of two timstamps, convert date format to a timestamp
private String getTimeDifference(String lastView) throws ParseException {
Long curTimeInMill = System.currentTimeMillis();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsedDate = format.parse(lastView);
Long lastViewInMillis = parsedDate.getTime();
Log.d("lastView", lastView);
Log.d("lastViewinMillis", String.valueOf(lastViewInMillis));
long diff = curTimeInMill - lastViewInMillis;
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
StringBuilder elapsedTime = new StringBuilder();
if (diffDays != 0) {
elapsedTime.append(String.valueOf(diffDays) + " Days" + " Ago");
} else if (diffHours != 0) {
elapsedTime.append(String.valueOf(diffHours) + " Hours" + " Ago");
} else if (diffMinutes != 0) {
elapsedTime.append(String.valueOf(diffMinutes) + " Minutes"
+ " Ago");
} else if (diffSeconds != 0) {
elapsedTime.append(String.valueOf(diffSeconds) + " Seconds"
+ " Ago");
}
Log.d("elapsedTime", elapsedTime.toString());
return elapsedTime.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment