获取具有 Java ThreeTen BP 的人的年龄
Get age of person with Java ThreeTen BP
我想找出一个人的年龄 - 给定他的生日(年、月、日)。我如何使用 ThreeTenBP 做到这一点?
编辑:
我找到的一个选项是这样的
LocalDate birthdate = LocalDate.of(year, month, day);
return (int) birthdate.until(LocalDate.now(), ChronoUnit.YEARS);
您的代码在大多数国家/地区都是正确的。它假定 2 月 29 日出生的人的生日是平年的 3 月 1 日。
阅读 Wikipedia.
然而,这使得 ThreeTen 与自身不一致,不像 Joda-time。
// if birthdate = LocalDate.of(2012, Month.FEBRUARY, 29);
System.out.println (birthdate.until(birthdate.plusYears(1), ChronoUnit.YEARS)); // display 0
如果您希望 getAge() 与 plusYears() 对称,您可以这样写:
public static int getAge(LocalDate birthdate, LocalDate today)
{
int age = today.getYears() - birthdate.getYears();
if (birthdate.plusYears(age).isAfter(today))
age--;
return age;
}
另请参阅:How do I calculate someone's age in Java?
我想找出一个人的年龄 - 给定他的生日(年、月、日)。我如何使用 ThreeTenBP 做到这一点?
编辑: 我找到的一个选项是这样的
LocalDate birthdate = LocalDate.of(year, month, day);
return (int) birthdate.until(LocalDate.now(), ChronoUnit.YEARS);
您的代码在大多数国家/地区都是正确的。它假定 2 月 29 日出生的人的生日是平年的 3 月 1 日。 阅读 Wikipedia.
然而,这使得 ThreeTen 与自身不一致,不像 Joda-time。
// if birthdate = LocalDate.of(2012, Month.FEBRUARY, 29);
System.out.println (birthdate.until(birthdate.plusYears(1), ChronoUnit.YEARS)); // display 0
如果您希望 getAge() 与 plusYears() 对称,您可以这样写:
public static int getAge(LocalDate birthdate, LocalDate today)
{
int age = today.getYears() - birthdate.getYears();
if (birthdate.plusYears(age).isAfter(today))
age--;
return age;
}
另请参阅:How do I calculate someone's age in Java?