1)假设您可以在输入字段中写入日期,并且日历只是图标。你可以有这样的辅助方法
public String threeDaysBefore(){
String threeDaysBefore = "";
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_YEAR, -3);
Date before = cal.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
threeDaysBefore = formatter.format(before);
return threeDaysBefore;
}
然后在代码中
WebElement calendarManualInput = driver.findElement...// find the manual input field
calendarManualInput.sendKeys(threeDaysBefore());
2)如果只能点击日历,那就有点麻烦了。您仍然需要字符串,但略有不同:
public String threeDaysBefore(){
String threeDaysBefore = "";
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_YEAR, -3);
Date before = cal.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd");
threeDaysBefore = formatter.format(before);
return threeDaysBefore;
}
但上面的内容没什么亮点。如果日期是1.4。那么它会返回“29”,可以解释为 29.4。这是你不希望发生的。所以稍后在代码中你可能需要这样做
//this will click three days before
Date today = new Date();
Date minusThree = new Date();
Calendar now = Calendar.getInstance();
now.setTime(today);
Calendar before = Calendar.getInstance();
before.setTime(minusThree);
before.add(Calendar.DAY_OF_YEAR, -3);
int monthNow = now.get(Calendar.MONTH);
int monthBefore = before.get(Calendar.MONTH);
if (monthBefore < monthNow){
// click previous month in the calendar tooltip on page
}
WebElement dateToSelect = driver.findElement(By.xpath("//span[text()='"+threeDaysBefore()+"']"));
dateToSelect.click();