<h1>Best Way To Compare Dates in Android</h1>
Sometimes we need to do a list with dates, like
today with hour
yesterday with yesterday
other days with 23/06/2017
To make this we need to compare current time with our data.
Example in GitHub
Public class DateUtil { Public static int getDateDayOfMonth (Date date) { Calendar calendar = Calendar.getInstance (); Calendar.setTime (date); Return calendar.get (Calendar.DAY_OF_MONTH); } Public static int getCurrentDayOfMonth () { Calendar calendar = Calendar.getInstance (); Return calendar.get (Calendar.DAY_OF_MONTH); } Public static String convertMillisSecondsToHourString (long millisSecond) { Date date = new Date (millisSecond); Format formatter = new SimpleDateFormat ("HH: mm"); Return formatter.format (date); } Public static String convertMillisSecondsToDateString (long millisSecond) { Date date = new Date (millisSecond); Format formatter = new SimpleDateFormat ("dd / MM / yyyy"); Return formatter.format (date); } Public static long convertToMillisSecond (Date date) { Return date.getTime (); } Public static String compare (String stringData, String yesterday) { String result = ""; SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss"); Date date = null; Try { Date = simpleDateFormat.parse (stringData); } Catch (ParseException e) { E.printStackTrace (); } Long millisSecond = convertToMillisSecond (date); Long currencyMillisSecond = System.currentTimeMillis (); If (currencyMillisSecond> millisSecond) { Long diff = currencyMillisSecond - millisSecond; Long day = 86400000L; If (diff <day && getCurrentDayOfMonth () == getDateDayOfMonth (date)) { Result = convertMillisSecondsToHourString (millisSecond); } Else if (diff <(day * 2) && getCurrentDayOfMonth () -1 == getDateDayOfMonth (date)) { Result = yesterday; } Else { Result = convertMillisSecondsToDateString (millisSecond); } } Return result; } }