计算java中两个日期之间的天数

Ang*_*yJS 7 java datetime date

我需要计算两个日期之间的天数,我使用下面的代码.问题是它返回我2但实际上它应该返回3因为2016年6月30日到6月27日之间的差异是3.你能帮助它应该包括当前日期以及差异吗?

public static long getNoOfDaysBtwnDates(String expiryDate) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Date expDate = null;
    long diff = 0;
    long noOfDays = 0;
    try {

        expDate = formatter.parse(expiryDate);
        //logger.info("Expiry Date is " + expDate);
       // logger.info(formatter.format(expDate));

        Date createdDate = new Date();
        diff = expDate.getTime() - createdDate.getTime();
        noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
        long a = TimeUnit.DAYS.toDays(noOfDays);
       // logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
        System.out.println(a);
        System.out.println(noOfDays);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return noOfDays;
}
Run Code Online (Sandbox Code Playgroud)

到期日为2016-06-30,当前日期为2016-06-27

PyT*_*hon 7

原因是,您没有使用相同的时间格式减去两个日期.

使用Calendar类将日期的时间更改为00:00:00,您将获得几天的确切差异.

Date createdDate = new Date();
Calendar time  = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
Run Code Online (Sandbox Code Playgroud)

吉姆加里森回答更多解释


Bal*_*des 5

为什么不用LocalDate

import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;

long diffInDays(LocalDate a, LocalDate b) {
  return DAYS.between(a, b);
}
Run Code Online (Sandbox Code Playgroud)