1. /*
    2. * Calculate the span of time from today until your birthday, assuming your
    3. * birthday occured on January 1st. The calculation is done using both
    4. * months and days (using Period) and days only (using ChronoUnit.between).
    5. * 计算距离下一次生日还有多长时间,假设生日在1月1日
    6. * 分别计算了还有几个月零几天和总共还有多少天
    7. */
    8. import java.time.LocalDate;
    9. import java.time.Month;
    10. import java.time.Period;
    11. import java.time.temporal.ChronoUnit;
    12. import java.io.PrintStream;
    13. public class Birthday {
    14. public static void main(String[] args) {
    15. LocalDate today = LocalDate.now();
    16. LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
    17. LocalDate nextBDay = birthday.withYear(today.getYear());
    18. //If your birthday has occurred this year already, add 1 to the year.
    19. if (nextBDay.isBefore(today) || nextBDay.isEqual(today)) {
    20. nextBDay = nextBDay.plusYears(1);
    21. }
    22. Period p = Period.between(today, nextBDay);
    23. long p2 = ChronoUnit.DAYS.between(today, nextBDay);
    24. System.out.println("There are " + p.getMonths() + " months, and " +
    25. p.getDays() + " days until your next birthday. (" +
    26. p2 + " total)");
    27. }
    28. }