1

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.");
    }

}
Pike D.
  • 671
  • 2
  • 11
  • 30

1 Answers1

2

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();
Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124
  • 1
    I'm still getting 5478, but it is not negative. I am going to assume something is wrong with the way I am receiving dates, and not really the syntax. Thank you for your help. – Pike D. Mar 03 '17 at 03:00
  • 1
    Did you consider most of the world uses a much more logical date format than the US.... *cough* dd/MM/yy ? (Not just being fascetious - it could be your format problem) – Nick Cardoso Mar 03 '17 at 03:05
  • I just checked over my code, sadly no. It looks like I messed up on inserting dates into the SQLite database. – Pike D. Mar 03 '17 at 03:10