Search code examples
javaandroidtimemillisecondsandroid-date

compare date with millisecond in android


I have date in this format "23-March-2003" and time in milliseconds which include date+time.

Now I want compare this date with millisecond either it is same date or not. how can I do this??


Solution

  • I guess this might work: (It is good practice to use Calendar)

    private boolean areEqual(String theDate, long currentTimeMillis) {
        try {
            Calendar c1 = Calendar.getInstance();
            c1.setTime(new SimpleDateFormat("dd-MMM-yyyy").parse(theDate));
            Calendar c2 = Calendar.getInstance();
            c2.setTime(new Date(currentTimeMillis));
            return ((c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR))
                    &&
               (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)));
    
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }
    

    Call the function like this:

    boolean result = areEqual("23-March-2003", System.currentTimeMillis());