0

我正在使用 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 日开始的一年中的日期,因此不计算正确的年龄。

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

4

2 回答 2

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

希望这可以帮助。

于 2013-03-05T18:38:53.837 回答
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;
}
于 2013-03-07T09:02:49.097 回答