How to get the time in Android relative to current time? - In number of seconds, minutes, hours or days ago
Many a time, we shall be dealing with time in a number of varied DateTime formats. We have discussed about some of the ways to standardize DateTime in a previous article. In this article, we shall learn how to get the time relative to current time.
Without further adieu, lets jump into the code. We shall be working with the input time in milliseconds (Refer this article on how to parse the date and get time in milliseconds). we then get the current time in milliseconds using System.currentTimeMillis().
long now = System.currentTimeMillis();
Then we check if currentTime is greater than inputTime, meaning the inutTime is in the past, and then find the difference between the inputTime and currentTime. We convert the difference to seconds, minutes, hours, days, months and years to determine its relativity. Check out the entire code below:
// inputTime in milliseconds public static String getRelativeTime(long inputTime) { long difference = 0; // Get the current time in milli seconds long currentTime = System.currentTimeMillis(); if (currentTime > inputTime) { difference = currentTime - inputTime; final long seconds = difference / 1000; final long minutes = seconds / 60; final long hours = minutes / 60; final long days = hours / 24; final long months = days / 31; final long years = days / 365; if (seconds < 60) { return seconds == 1 ? "one second ago" : seconds + " seconds ago"; } else if (seconds < 120) { return "a minute ago"; } else if (seconds < 2700) { // 45 * 60 return minutes + " minutes ago"; } else if (seconds < 5400) { // 90 * 60 return "an hour ago"; } else if (seconds < 86400) { // 24 * 60 * 60 return hours + " hours ago"; } else if (seconds < 172800) { // 48 * 60 * 60 return "Yesterday"; } else if (seconds < 2592000) { // 30 * 24 * 60 * 60 return days + " days ago"; } else if (seconds < 31104000) { // 12 * 30 * 24 * 60 * 60 return months <= 1 ? "One month ago" : days + " months ago"; } else { return years <= 1 ? "One year ago" : years + " years ago"; } } return null; }