Search code examples
javaandroidcomparisonandroid-date

Date comparison not working


I am trying to compare two dates by subtracting and then dividing the milliseconds into days, but this returns everytime -5479. Is there something wrong with my syntax? I don't know why this is happening.

if (task_date_view != null) {
    Date current_date = new Date();
    String myFormat = "MM/dd/yy";
    DateFormat dateFormat = new SimpleDateFormat(myFormat);
    Date temp_date;
    try {
        temp_date = dateFormat.parse(list_task.getDate());
        long difference = temp_date.getTime() - current_date.getTime();
        long diffDays = difference / (24 * 60 * 60 * 1000);
        String date_string = Long.toString(diffDays);
        task_date_view.setText(date_string + " days left.");

    } catch (ParseException e) {
        task_date_view.setText("No days left.");
    }

}

Solution

  • I think most likely if you're comparing to a date in the past (e.g time remaining on a license), you're getting a negative because this is backwards:

    temp_date.getTime() - current_date.getTime()
    

    How about this to get difference in days:

    long end = endDate.getTime();
    long start = startDate.getTime();
    int daysDiff = TimeUnit.MILLISECONDS.toDays(Math.abs(end - start));
    

    If you want a date difference from now, then use:

    long start = System.currentTimeInMillis();