2013-03-05 4 views
0

자동화를 위해 Selenium Webdriver를 사용하고 있으며 현재 사람의 나이를 검색하여 응용 프로그램에 입력 된 나이와 비교해야합니다.Selenium WebDriver를 사용하여 연령대를 비교하는 중

내 코드 진행과 같은 :

String DOB = driver.findElement(By.id("")).getAttribute("value"); 
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); 
Date convertedDate = dateFormat.parse(DOB); 

Calendar currentDate = Calendar.getInstance(); 
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); 
Date currentNow = currentDate.getTime(); 

System.out.println("Sys date: " + currentNow); 
System.out.println("DOB Date: " + convertedDate); 

출력 : 나는 응용 프로그램의 나이가 자동으로 입력되는과 비교할 수 있도록 내가 적절한 나이를 검색 할 수있는 방법

Sys date: Tue Mar 05 12:25:19 IST 2013 
DOB Date: Wed Mar 15 00:00:00 IST 1967 

. 현재 .getYear()을 사용하여 빼기를하면 1 월 1 일부터 시작하는 연월일을 가정하므로 적절한 나이를 계산하지 않습니다.

올바른 나이를 성공적으로 계산할 수 있도록 도와주세요.

+0

이 링크가 귀하의 목적에 부합하는지 확인하십시오. http://www.javahelpandsupport.in/2011/09/program-for-calculating-age-of-person.html – Hemanth

답변

0

이미 몇 년을 비교해 본 사람이라면 월/일을 현재 날짜와 비교해보십시오. 캘린더는 약간의 코이 킹으로이 작업을 수행 할 수 있습니다.

//Retrieve date from application 
    String DOB = driver.findElement(By.id("")).getAttribute("value"); 

    //Define the date format & create a Calendar for this date 
    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy"); 
    Calendar birthday = Calendar.getInstance(); 
    birthday.setTime(sdf.parse(DOB)); 

    //Create a Calendar object with the current date 
    Calendar now = Calendar.getInstance(); 

    //Subtract the years to get a general age. 
    int diffYears = now.get(Calendar.YEAR) - birthday.get(Calendar.YEAR); 

    //Set the birthday for this year & compare 
    birthday.set(Calendar.YEAR, now.get(Calendar.YEAR)); 
    if (birthday.after(now)){ 
     //If birthday hasn't passed yet this year, subtract a year 
     diffYears--; 
    } 

희망이 있습니다.

0

이것이 도움이되는지 확인하십시오. 이 방법은 정확한 년 수를 제공합니다.

public static int getDiffYears(Date first, Date last) { 
    Calendar a = getCalendar(first); 
    Calendar b = getCalendar(last); 
    int diff = b.get(YEAR) - a.get(YEAR); 
    if (a.get(MONTH) > b.get(MONTH) || 
     (a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) { 
     diff--; 
    } 
    return diff; 
} 
관련 문제