java - 如何使用 Joda 时间库计算下一个生日

标签 java date time android-jodatime

我有两个日期,格式如下 出生日期假设 1995/04/09 和当前日期 2016/07/24 那么我怎样才能获得到下一个生日的剩余月份和天数

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;
}

请任何人帮助我提前致谢

最佳答案

根据您的问题,您想使用 Joda 计算下一个生日。 下面的代码将帮助您给出即将到来的生日月份。

   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 currentYearBirthDay = new LocalDate().withDayOfMonth(birthDay)
                        .withMonthOfYear(birthMonth);
   PeriodType monthDay = PeriodType.yearMonthDayTime().withYearsRemoved();
   PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
        .appendMonths().appendSuffix(" Months ").appendDays()
        .appendSuffix(" Days ").printZeroNever().toFormatter();
   if (currentYearBirthDay.isAfter(currentDate)) {
       Period period = new Period(currentDate, currentYearBirthDay,monthDay );
       String currentBirthday = periodFormatter.print(period);
       System.out.println(currentBirthday );
   } else {
        LocalDate nextYearBirthDay =currentYearBirthDay.plusYears(1);
        Period period = new Period(currentDate, nextYearBirthDay ,monthDay );
        String nextBirthday = periodFormatter.print(period);
        System.out.println(nextBirthday);
   }

输出:

8 Months 16 Days

关于java - 如何使用 Joda 时间库计算下一个生日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38552679/

相关文章:

java - 反序列化时未调用构造函数

java - 在字符串变量上使用 ?eval 时,Freemarker 返回 null

javascript - 从给定的月份和年份输入中获取一个月的哪一天开始

sql - 获取计数行的最后一个实例

ios - StoreKit - 如何获得正确的有效期?

Python按增量修改csv列

用于下载 Artifactory 并进行比较的java程序

java - 当netty连接到我的服务器时?

python - Selenium Python - 显式等待不起作用

python - 如何在Python中添加定时延迟以进行硬件控制