java.time and ThreeTenABP
My suggestion is using java.time, the modern Java date and time API:
public static int daysRemain(LocalDate dob){
LocalDate today = LocalDate.now(ZoneId.of("Asia/Kolkata"));
long age = ChronoUnit.YEARS.between(dob, today);
LocalDate nextBirthday = dob.plusYears(age);
if (nextBirthday.isBefore(today)) {
nextBirthday = dob.plusYears(age + 1);
}
long daysUntilNextBirthday = ChronoUnit.DAYS.between(today, nextBirthday);
return Math.toIntExact(daysUntilNextBirthday);
}
Let’s try it out:
System.out.println(daysRemain(LocalDate.of(1999, Month.MAY, 28)));
When I ran this call today (25th May in India), the output was:
3
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