This is a small part of an Android application I’m working on; couldn’t find a simple Java relative date function so here’s one I made.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
public static String getRelativeDate(long timestamp) { Calendar secondDate = Calendar.getInstance(); secondDate.setTimeInMillis(timestamp * 1000); Calendar currentDate = Calendar.getInstance(); int yearDifference = secondDate.get(Calendar.YEAR) - currentDate.get(Calendar.YEAR); int monthDifference = secondDate.get(Calendar.MONTH) - currentDate.get(Calendar.MONTH); int dayDifference = secondDate.get(Calendar.DAY_OF_MONTH) - currentDate.get(Calendar.DAY_OF_MONTH); int hourDifference = secondDate.get(Calendar.HOUR) - currentDate.get(Calendar.HOUR); int minuteDifference = secondDate.get(Calendar.MINUTE) - currentDate.get(Calendar.MINUTE); int secondDifference = secondDate.get(Calendar.SECOND) - currentDate.get(Calendar.SECOND); if(yearDifference >= 1 || yearDifference < -1) { return createDifference("year", yearDifference); } else if(monthDifference >= 1 || monthDifference < -1) { return createDifference("month", monthDifference); } else if(dayDifference >= 1 || dayDifference < -1) { return createDifference("day", dayDifference); } else if(hourDifference >= 1 || hourDifference < -1) { return createDifference("hour", hourDifference); } else if(minuteDifference >= 1 || minuteDifference < -1) { return createDifference("minute", minuteDifference); } else if(secondDifference >= 1 || secondDifference < -1) { return createDifference("second", secondDifference); } else { return "Now"; } } private static String createDifference(String part, int difference) { String s = (Math.abs(difference) > 1) ? "s" : ""; if(difference >= 1) { return String.format("In %d %s%s", difference, part, s); } else { return String.format("%d %s%s ago", Math.abs(difference), part, s); } } |
Questions? Comments?