我想将出生日期转换为年龄。 这是我的代码。
String patientDOB = driver.findElement(id("patient_profile_widget_form_birthday")).getAttribute("value");
我的约会日期是:1961年3月1日
我该如何将其转换为年龄? 我想要类似=> 57 Years
的输出有什么主意吗? :)
答案 0 :(得分:1)
使用Java 8
public int calculateAge(
LocalDate birthDate) {
// validate inputs ...
return Period.between(birthDate, LocalDate.now());
}
答案 1 :(得分:0)
private static final DateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
String patientDOB = driver.findElement(id("patient_profile_widget_form_birthday")).getAttribute("value");
Date dateOfBirth = getDateFromString(patientDOB);
public Date getDateFromString(final String patientDOB) {
try {
return FORMATTER.parse(param);
} catch (ParseException e) {
throw new Exception("ParseException occurred while parsing date ", e);
}
}
public static int getAge(Date dateOfBirth) {
Calendar today = Calendar.getInstance();
Calendar birthDate = Calendar.getInstance();
birthDate.setTime(dateOfBirth);
if (birthDate.after(today)) {
throw new IllegalArgumentException("You don't exist yet");
}
int todayYear = today.get(Calendar.YEAR);
int birthDateYear = birthDate.get(Calendar.YEAR);
int todayDayOfYear = today.get(Calendar.DAY_OF_YEAR);
int birthDateDayOfYear = birthDate.get(Calendar.DAY_OF_YEAR);
int todayMonth = today.get(Calendar.MONTH);
int birthDateMonth = birthDate.get(Calendar.MONTH);
int todayDayOfMonth = today.get(Calendar.DAY_OF_MONTH);
int birthDateDayOfMonth = birthDate.get(Calendar.DAY_OF_MONTH);
int age = todayYear - birthDateYear;
// If birth date is greater than todays date (after 2 days adjustment of leap year) then decrement age one year
if ((birthDateDayOfYear - todayDayOfYear > 3) || (birthDateMonth > todayMonth)){
age--;
// If birth date and todays date are of same month and birth day of month is greater than todays day of month then decrement age
} else if ((birthDateMonth == todayMonth) && (birthDateDayOfMonth > todayDayOfMonth)){
age--;
}
return age;
}
答案 2 :(得分:-2)
创建一个包装器方法,将字符串作为参数,
使用:
String[] parts = string.split("/");
,然后选择列表的第三项。
然后您只需要使用:
int year = Calendar.getInstance().get(Calendar.YEAR);
得到你的一年。然后,您只需将年份字符串转换为int并将其减去