Shareque Shareque - 4 months ago 31
Java Question

How to calculate next birthday using Joda time libaray

I have two dates in format like
Date of birth suppose 1995/04/09 and current date 2016/07/24
so how can I get Months and Days remaining to next birthday

public String getNextBirthdayMonths() {
LocalDate dateOfBirth = new LocalDate(startYear, startMonth, startDay);
LocalDate currentDate = new LocalDate();

Period period = new Period(dateOfBirth, currentDate);
PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
.appendMonths().appendSuffix(" Months ")
.appendDays().appendSuffix(" Days ")
.printZeroNever().toFormatter();

String nextBirthday = periodFormatter.print(period);
return "" + nextBirthday;
}


Please anyone help me Thanks in advance

Answer

You want to calculate the next birthday using Joda. The below code will help you to give the coming birthday months.

LocalDate dateOfBirth = new LocalDate(1995, 4, 9);
LocalDate currentDate = new LocalDate();
// Take birthDay  and birthMonth  from dateOfBirth 
int birthDay = dateOfBirth.getDayOfMonth();
int birthMonth = dateOfBirth.getMonthOfYear();
// Current year's birthday
LocalDate currentBirthDay = new LocalDate().withDayOfMonth(birthDay)
                .withMonthOfYear(birthMonth);
PeriodType monthDay = PeriodType.yearMonthDayTime().withYearsRemoved();
if (currentBirthDay.isAfter(currentDate)) {
    Period period = new Period(currentDate, currentBirthDay,monthDay );
    PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
            .appendMonths().appendSuffix(" Months ").appendDays()
            .appendSuffix(" Days ").printZeroNever().toFormatter();
    String currentBirthday = periodFormatter.print(period);
    System.out.println(currentBirthday );
} else {
    LocalDate nextYearBirthDay =currentYearBirthDay.plusYears(1);
    Period period = new Period(currentDate, nextYearBirthDay ,monthDay );
    PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
            .appendMonths().appendSuffix(" Months ").appendDays()
            .appendSuffix(" Days ").printZeroNever().toFormatter();
    String nextBirthday = periodFormatter.print(period);
    System.out.println(nextBirthday);
}

Output:

8 Months 16 Days