简体   繁体   中英

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

}

I think most likely if you're comparing to a date in the past (eg 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM