In this post I will give you a code how to automate
selection of date from a date widget neither has the date input and also direct
navigation to the months/years. This widget only has the 'Prev', 'Next' buttons
to navigate to next months/previous months.
Please find the code below:
public class DateWidgetSample {
public static void main(String args[]){
String
date1="12/04/2016";
String
date2="12/12/2015";
SimpleDateFormat fmt=
new SimpleDateFormat("dd/MM/yyyy");
Date datevar1 = null;
Date datevar2 = null;
try {
datevar1 =
fmt.parse(date1);
datevar2 =
fmt.parse(date2);
} catch
(ParseException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
Calendar cal1 =
Calendar.getInstance();
Calendar cal2 =
Calendar.getInstance();
cal1.setTime(datevar1);
cal2.setTime(datevar2);
cal1.set(Calendar.DAY_OF_MONTH, 1);
cal2.set(Calendar.DAY_OF_MONTH, 1);
int diffYear =
cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR);
int diffMonth =
diffYear * 12 + cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);
System.out.println(diffMonth);
}
}
Result output is difference of months.
Next you have to do is have a for loop to click the
previous/next button based on the number of months obtained in the output. If
the number is a positive value, ask to click the next button. If it's a
negative value, click the Previous button. That's all. Check code below.
if(diffMonth>0){
for(int i=0; i<diffMonth; i++){
driver.findElement(By.id("nextbtn").click();
}
}
if(diffMonth<0){
for(int j=0; j<diffMonth; j++){
driver.findElement(By.id("previousbtn").click();
}
}