2013-03-05 82 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 2013-03-05 07:26:13

回答

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; 
}