比较使用Selenium WebDriver填充的年龄

时间:2013-03-05 07:02:06

标签: java selenium 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日开始的年份日期,因此不计算适当的年龄。

请帮助我,以便我能成功计算出正确的年龄。

2 个答案:

答案 0 :(得分: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--;
    }

希望这会有所帮助。

答案 1 :(得分: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;
}