我正在尝试从Jdatechooser获取所选日期并在Textfield中显示与日期对应的年龄,我看到所有线程都在讨论这个问题,但它对我不起作用。我的代码是:
private void datenaiss_choozPropertyChange(java.beans.PropertyChangeEvent evt) {
Date date = (Date) datenaiss_chooz.getDate();
LocalDate ld = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Period p =Period.between(ld, LocalDate.now());
age.setText(p);
}
答案 0 :(得分:1)
使用joda-time解决您的问题:
DateTime birthDate = new DateTime(1990, 1, 15, 0, 0, 0, 0);
DateTime now = new DateTime();
Period period = new Period(birthDate, now);
int years = period.getYears();
System.out.println(years);
这将为您提供所需的差异!
答案 1 :(得分:0)
终于在很长一段时间后我得到了解决方案,感谢所有人帮助我。这是我的代码完美运行:
DateTime start = new DateTime(datenaiss_chooz.getDate());
Years h = Years.yearsBetween(start, new DateTime());
StringBuilder b = new StringBuilder();
b.append(h.getYears());
String str = b.toString();
if ( h.getYears()==0)
age.setText("");
else
age.setText(str+" "+"ans");