Function for selecting Date from calendar in selenium

Function for selecting Date from calendar in selenium

The select Date function facilitates the selection of a specific date from a calendar interface on a web page. It automates the process of interacting with the calendar widget to choose the desired date.

Parameters:

monthYear: A string indicating the target month and year in the format “Month Year” (e.g., “March 2024”).

day: A string representing the day of the month to be selected (e.g., “15”).

Steps:

Click on Start Date Element: This step initiates the selection process by clicking on the element associated with the start date on the web page. This action typically opens the calendar widget for date selection.

Wait for Calendar to Load: The function pauses execution for 2000 milliseconds (2 seconds) to allow the calendar widget to fully load. This ensures that subsequent interactions with the calendar occur after it has been rendered completely.

Check Current Month and Year: It compares the current month and year displayed in the calendar with the provided monthYear. If they do not match, the function proceeds to the next step; otherwise, it skips to step 5.

Navigate to Target Month and Year:

If the current month and year displayed in the calendar do not match the provided monthYear, the function enters a loop to iteratively navigate to the next month by clicking on the forward navigation option. This continues until the displayed month and year align with the provided values.

Select Target Date: Once the correct month and year are displayed, the function locates the element corresponding to the desired day in the calendar using an XPath expression. It then clicks on this element to select the specified date.

Example:

public void selectTravelDate(String monthYear, String day) throws InterruptedException {

startDate.click();

Thread.sleep(2000);

if (!curMnthYr.getText().contentEquals(monthYear)) {

do {

forwardOption_Calendar.click();

} while (!curMnthYr.getText().contentEquals(monthYear));

}

WebElement dateSel = getDriver().findElement(By.xpath(“//li[contains(text(),'”+day+”‘)]”));

dateSel.click();

}

Ensure that the elements startDate, curMnthYr, forwardOption_Calendar, and the getDriver() method are properly initialized and accessible within the scope of this function.

This function assumes a consistent behavior of the calendar widget and relies on the accuracy of its display for selecting dates.

Leave a comment

Your email address will not be published. Required fields are marked *