Days between dates showing float value
I have written a code to calculate number of days between dates in following way
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = date.parse(startDate);
Date date2 = date.parse(endDate);
long difference = (date2.getTime()-date1.getTime())/(24*60*60*1000);
My job is to find whether term between startDate and endDate is exactly one year.
i am initially checking year type(whether leap year/normal year) after calculating difference between dates.
if non leap year, then i will check whether difference is 365
if leap year, then i will check whether difference is 366.
But for few dates in november say
startDate = 11/04/2015(MM/dd/yyyy) endDate = 11/04/2016(MM/dd/yyyy)
difference is calculated as 365 where code is expecting 366 as endDate year 2016 is a leap year and also end date's month is after february.
What really happening is absolute difference we are getting is 365.9 but not 366.0
This is happening for only few dates of november as per my observations.
11/02/2015 to 11/02/2016, 11/03/2015 to 11/03/2016 , 11/04/2015 to 11/04/2016, 11/05/2015 to 11/05/2016,11/06/2015 to 11/06/2016.
For remaining i am seeing difference as 366.0.
My question is, Why this peculiar behavior we are seeing for these few dates only. What is the problem with date.getTime when it always returns milliseconds passed since January 1, 1970, 00:00:00 GMT.
Use a DateTime API. Since Java 8 got this you should use it like this:
private static boolean isYearBetween(String start, String end) {
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate startDate = LocalDate.parse(start, pattern);
LocalDate endDate = LocalDate.parse(end, pattern);
Period between = Period.between(startDate, endDate).normalized();
return Period.ofYears(1).equals(between.isNegative() ? between.negated() : between);
}
Why not use the new feature that comes with java 8: java.time.LocalDateTime? You can then easily format your dates and time with java.time.format.DateTimeFormatter. For leap years as well, it works better than java.Date.
LocalDate date = LocalDate.parse("yyyy-MM-dd");
LocalDate date1 = date.parse(startDate);
LocalDate date2 = date.parse(endDate);
I run your code, I got 366
SimpleDateFormat date = new SimpleDateFormat("MM/dd/yyyy");
Date date1 = date.parse("11/02/2015");
Date date2 = date.parse("11/02/2016");
long difference = (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000);
System.out.println("Difference " + difference);
Output
Difference 366
Same for all other dates in the question.
For non-leap years it prints 365
as expected.
上一篇: C#将日期添加到给定的日期
下一篇: 显示浮点值的日期之间的天数