Assumption - you have a java.util.Date
input and you want a java.util.Date
output.
First recommendation - stop using java.util.Date
. The newer java.time
API is better implemented and, once you get use to using it, easier to use
Ok, first, we want to convert the java.util.Date
to a java.time.LocalDate
...
public LocalDate toLocalDate(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
From there, it's a simple case of just adding another year...
LocalDate nextBirthDate = toLocalDate(someDate).plusYear(1);
Remember, java.time
objects are not mutable.
Finally, you can convert the LocalDate
back to a java.util.Date
if required
public Date toUtilDate(LocalDate dateToConvert) {
return java.util.Date.from(dateToConvert.atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant());
}
but this raises a bunch of questions over why you'd even bother (going back to java.util.Date
). Once you can get out of that API and into the newer java.time
API, you should try and stay there (IMHO)
nb Date conversations from Convert Date to LocalDate or LocalDateTime and Back
"from" and "with" seemed the most promising..but ultimately don't support this use case (i.e. cannot give the next instance of LocalDate given a Day and Month)
Still not seeing the issue. The following examples takes a original birthdate, the current and determines the "next" birthdate based on if the current "year date" is before or after today
LocalDate orignalBirthDate = LocalDate.of(1972, Month.MARCH, 8);
LocalDate today = LocalDate.now();
int year = today.getYear();
LocalDate nextBirthDate = orignalBirthDate.withYear(year);
if (nextBirthDate.isBefore(today)) {
nextBirthDate = nextBirthDate.plusYears(1);
}
System.out.println("Next birthday = " + DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(nextBirthDate));