我想计算患者的年龄。主要问题是计算在Java Time开始之前出生的患者。此代码在Java控制台应用程序中工作正常,但在基于JSF和JPA的实体中失败。我只在实体和年龄中记录出生数据是一种短暂的属性。我无法弄清楚为什么相同的代码无法在Java EE应用程序中运行。
public String getAge() {
System.out.println("getting age");
if (person == null) {
System.out.println("patient is null");
age = "";
return age;
}
if (person.getDob() == null) {
System.out.println("dob is null");
age = "";
return age;
}
System.out.println("this = " + this);
System.out.println("Person = " + Person);
Date dob = person.getDob();
System.out.println("dob = " + dob);
if (dob == null) {
System.out.println("dob is null");
age = "";
return age;
}
long temAge;
long dobTime = dob.getTime();
System.out.println("dobTime = " + dobTime);
long nowTime = Calendar.getInstance().getTime().getTime();
System.out.println("nowTime = " + nowTime);
if (dobTime < 0) {
System.out.println("dobTime = " + dobTime);
temAge = (nowTime + Math.abs(dobTime));
System.out.println("nowTime = " + nowTime);
System.out.println("Math.dob = " + Math.abs(dobTime));
System.out.println("temAge = " + temAge);
temAge = temAge / (1000 * 60 * 60 * 24);
System.out.println("temAge = " + temAge);
System.out.println("age in days before is minus. now age in days is " + temAge);
} else {
temAge = (nowTime - dobTime) / (1000 * 60 * 60 * 24);
System.out.println("age in days before is minus. now age in days is " + temAge);
}
if (temAge < 60) {
age = temAge + " days";
} else if (temAge < 366) {
age = (temAge / 30) + " months";
} else {
age = (temAge / 365) + " years";
}
System.out.println("age is " + age);
return age;
}
编辑:
在完成Kaushal的答案后,我改变了我的代码。使用jodatime非常容易。感谢Kaushal的帮助。
public static String getAge() {
LocalDate birthdate = new LocalDate(getDob());
LocalDate now = new LocalDate();
Years ageInYears;
ageInYears = Years.yearsBetween(birthdate, now);
if (ageInYears.getYears() > 0) {
return ageInYears.getYears() + " Years";
} else {
Months ageInMonths = Months.monthsBetween(birthdate, now);
if (ageInMonths.getMonths() > 0) {
return ageInMonths.getMonths() + " Months";
} else {
Days ageInDays = Days.daysBetween(birthdate, now);
return ageInDays.getDays() + " Days";
}
}
}
答案 0 :(得分:5)
如果可能,请尝试使用jodatime。它是一个非常好的日期工具。
public static void main(String[] args) {
LocalDate birthdate = new LocalDate (1958, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
System.out.println(age.getYears());
}
你的意思是失败了。你有错误或年龄无效吗?
答案 1 :(得分:0)
年岁= Years.yearsBetween(new LocalDate(model.getDob()),new LocalDate()); years.getYears();
model.getDob()是java.util对象