LocalDate
减去一个Period
(例如"28年1个月27天")会得到错误的结果。
但是,减去一个仅包含天数单位的Period
(例如"10282"天)会得到正确的结果。有什么需要注意的吗?
public static void main(String[] args) {
printAgeAndBirthday(1989, 2, 22);
printBirthdayFromPeriod(28, 1, 27);
}
private static void printBirthdayFromPeriod(int years, int months, int days) {
final Period period = Period.of(years, months, days);
final LocalDate now = LocalDate.now();
final LocalDate birthday = now.minus(28, ChronoUnit.YEARS)
.minus(1, ChronoUnit.MONTHS)
.minus(27, ChronoUnit.DAYS);
System.out.println("your birthday is : "+ birthday);//1989-02-19
System.out.println("your birthday is : "+ now.minusYears(28).minusMonths(1).minusDays(27));//1989-02-19
System.out.println("your birthday is : "+ now.minus(period));//1989-02-19
System.out.println("your birthday is : "+period.subtractFrom(now));//1989-02-19
System.out.println("your birthday is : "+ now.minus(Period.ofDays(10282)));//1989-02-22
}
private static void printAgeAndBirthday(int year, int month, int dayOfMonth) {
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(year, month, dayOfMonth);
Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);
System.out.printf("You are %d years, %d months, and %d days old. (%d days total)%n",
p.getYears(), p.getMonths(), p.getDays(), p2);
LocalDate nextBDay = birthday.withYear(today.getYear());
//If your birthday has occurred this year already, add 1 to the year.
if (nextBDay.isBefore(today) || nextBDay.isEqual(today)) {
nextBDay = nextBDay.plusYears(1);
}
Period p_1 = Period.between(today, nextBDay);
long p_2 = ChronoUnit.DAYS.between(today, nextBDay);
System.out.printf("There are %d months, and %d days until your next birthday. (%d total)%n",
p_1.getMonths(), p_1.getDays(), p_2);
}
控制台日志:
You are 28 years, 1 months, and 27 days old. (10282 days total)
There are 10 months, and 4 days until your next birthday. (310 total)
your birthday is : 1989-02-19
your birthday is : 1989-02-19
your birthday is : 1989-02-19
your birthday is : 1989-02-19
your birthday is : 1989-02-22
java version : jdk1.8.0_45