我有出生日期,可以获得当前日期。
在java中,如何在计算闰年的同时计算某人的年龄?
编辑:我可以使用unix时间戳并比较差异吗?
答案 0 :(得分:8)
您可能知道java 8的日期和时间API更改受到Jodatime库本身的启发,因此使用java 8的下一个解决方案看起来与上面的代码示例几乎相似:
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
Period p = Period.between(birthday, today);
//Now access the values as below
System.out.println(p.getDays());
System.out.println(p.getMonths());
System.out.println(p.getYears());
答案 1 :(得分:1)
LocalDate birthdate = new LocalDate (1990, 12, 2);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
答案 2 :(得分:1)
在Java 8
:
LocalDate startDate = LocalDate.of(1987, Month.AUGUST, 10);
LocalDate endDate = LocalDate.of(2015, Month.MAY, 27);
long numberOfYears = ChronoUnit.YEARS.between(startDate, endDate);
使用Java 8
日期的好例子:
Java 8 Date Examples
答案 3 :(得分:0)
正如@MadProgrammer建议的那样,您可以使用JodaTime
。
以下是示例代码。
LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
答案 4 :(得分:-2)
怎么样:
Date birthDate = new Date(85, 03, 24);
GregorianCalendar birth = new GregorianCalendar();
birth.setTime(birthDate);
int month = birth.get(GregorianCalendar.MONTH);
int day = birth.get(GregorianCalendar.DAY_OF_MONTH);
GregorianCalendar now = new GregorianCalendar();
int age = now.get(GregorianCalendar.YEAR) - birth.get(GregorianCalendar.YEAR);
int birthMonth = birth.get(GregorianCalendar.MONTH);
int birthDay = birth.get(GregorianCalendar.DAY_OF_MONTH);
int nowMonth = now.get(GregorianCalendar.MONTH);
int nowDay = now.get(GregorianCalendar.DAY_OF_MONTH);
if (nowMonth>birthMonth) {
age = age+1;
} else {
if (nowMonth == birthMonth) {
if (nowDay >= birthDay) {
age= age+1;
}
}
}
System.out.println("Now it is my " + age+ " year of life");