AngryJS AngryJS - 1 year ago 147
Java Question

Calculate no of days between two dates in java

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);
//"Expiry Date is " + expDate);

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

} catch (ParseException e) {

return noOfDays;

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

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download