使用joda-time
您可以使用Period在joda time
api中实现此功能.尝试这样的事情:
Period period = new Period(d1, d2);// d1,d2 are Date objects System.out.print("You are " + period.getYears() + " years old");
使用java.time
如果你可以使用java.time类LocalDate
和Java 8或更高版本Period
,那么它可以这样实现:
LocalDate today = LocalDate.now(); LocalDate birthday = LocalDate.of(1990, Month.DECEMBER, 12); Period p = Period.between(birthday, today); System.out.println("You are " + p.getYears() + " years old");
产量
You are 25 years old