How to handle Calendar in Selenium WebDriver

Lets see how to handle calendar in a dynamic way.

There may be several approaches to handle calendar controls.

Here, I am going to show the dynamic way to select a particular Date, Month and year in a Calendar.

In some calendar controls, the months & years can be changed using navigation controls like previous and next buttons.

Approach to handle calendar in Java Selenium framework

Step 1 - Initiate WebDriver and set the application's URL where a Calendar is implemented.

Define the xpath with the Calendar control's id (in this example it is - travel_date) from the html source to find the element and later use that object to initiate the click action.

Step 2 - The Java program should wait until the calendar element has been loaded (that means Visible on screen). Note - For this you have to import Selenium's WebDriverWait library.

When the calendar pop up has been displayed on the screen (see image below). The program will have its element reference initiated. This is achieved using the locator By.Classname, in this e.g. the control's class name is datepicker-days.

Note: Some calendar's have a different look, style, and class names, but this Selenium logic will work for almost all of them.

Calendar Control

Code Snippet:

Step 3 - Create a Java method to isolate the data selection logic, and define parameters to hold the values for Expected Date, Expected Month and Expected Year.

Now, first read the displayed month and year on the calendar wizard, into a variable. This can be find using the class name locator, in this case it is datepicker-switch.

Example value - May 2022.

Until the Expected Month and Expected Year are matched on this displayed month and year, keep looping and navigate the calendar using Next or Previous clicks.




For this I have used while loop to get the text of the display date. Store this value in to a variable.

String MonthYear = driver.findElement(By.className("datepicker-switch")).getText();

Split the Month and Year based using the space delimiter, on the above value and then based of indexes capture month and year values. Month is in the 0th index and Year is in the 1st index.

I have created another small method to isolate the splitting logic to return the month, year values

Finally when the Expected Month and Expected Year is highlighted on the element, proceed to select the Expected Date and trigger the click action.

Code Snippet:

Approach to handle Invalid dates

To validate the dates that are not available on the calendar like for example - Feb 30 and June 32.

We need to include few conditions in the SelectDate Method to show the error message to the user.

Code Snippet:

I hope this blog will help you to work with calendar controls in your Selenium projects.

Please follow my blogs, Thank you.

1,623 views0 comments

Recent Posts

See All