Как преобразовать человека мм / дд / гггг DOB в фактический возраст. Селен, Ява
Я хочу преобразовать дату рождения в возраст. Это мой код
String patientDOB = driver.findElement(id("patient_profile_widget_form_birthday")).getAttribute("value");
Я получаю дату как: 01.03.1961
Как я могу преобразовать это в возраст? Я хочу вывод, как => 57 лет
Любая идея?:)
3 ответа
Используя Java 8
public int calculateAge(
LocalDate birthDate) {
// validate inputs ...
return Period.between(birthDate, LocalDate.now());
}
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;
}
Создайте метод-обертку, который получит строку в качестве аргумента,
использовать:
String[] parts = string.split("/");
и выберите 3-й пункт списка.
тогда вам просто нужно использовать:
int year = Calendar.getInstance().get(Calendar.YEAR);
чтобы получить свой год. Затем вы просто конвертируете свою строку года в int и вычитаете их