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