Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate no of days between two dates in java [duplicate]

I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?

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;
}

expiry date is 2016-06-30 and current date is 2016-06-27

like image 530
AngryJS Avatar asked Jun 27 '16 06:06

AngryJS


1 Answers

Reason is, you are not subtracting two dates with same time format.

Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.

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();

More explaination in Jim Garrison' answer

like image 194
PyThon Avatar answered Oct 06 '22 00:10

PyThon