Calculate the number of days between two dates in Java
•
Java
See English answers > Android / Java – date difference in days17
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; }
The expiration date is June 30, 2016, and the current date is June 27, 2016
Solution
The reason is that you did not subtract two dates using the same time format
Use the calendar class to change the time of the date to 00:00:00, and you will get the exact difference of several 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 explanations in Jim Garrison's answer
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码