java.time and ThreeTenABP
If I understand correctly, you want the number of days from start day through end date inclusive.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
String startDate = "2/3/2017";
String endDate = "3/3/2017";
LocalDate startDateValue = LocalDate.parse(startDate, dateFormatter);
LocalDate endDateValue = LocalDate.parse(endDate, dateFormatter);
long days = ChronoUnit.DAYS.between(startDateValue, endDateValue) + 1;
System.out.println("Days: " + days);
Output:
Days: 2
ChronoUnit.DAYS.between()
gives us a count of days from start date inclusive to end date exclusive. So to include the end date too we needed to add 1 day just as you did in the question.
What went wrong in your code?
You are using the Date(String)
constructor. This constructor has been deprecated since 1997 because it works unreliably across time zones, so don’t use it. Also it’s kind of magical: at least I never really know what I get. Apparently it takes 2/3/2017
to mean February 3, 2017, where you intended 2 March 2017. From February 3 to March 3 inclusive is 29 days (since 2017 wasn’t a leap year). This explains why you got 29. (If necessary, we could spell our way through the documentation and find out why 2/3/2017
is interpreted the way it is, only I’d find that a pointless waste of time to do.)
You can’t convert from milliseconds. Please also note that not only the question but also the very many answers that convert from milliseconds to days are incorrect. Such a conversion assumes that a day is always 24 hours. Because of summer time (DST) and other time anomalies a day is not always 24 hours. All of those answers will count a day too few for example if the leave crosses the spring gap or spring forward when summer time begins.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links