Selecting a date from a calendar widget is one of the most common tasks in UI automation. And yet, it often turns into a tricky challenge, especially when the datepicker behaves differently on each site.
Sometimes it's a jQuery calendar, sometimes it's a custom airline-style picker, and in many cases, it doesn't respond well to direct input. If you've ever wrestled with a flaky test just to select one simple date, you're not alone.
This guide walks you through exactly how to handle a datepicker in Selenium using Java. You’ll learn how to:
We’ll also walk through a real-world example from MakeMyTrip to show how to automate date selection from a live travel calendar.
If you're looking to master date picker automation in Selenium WebDriver with Java, this article will give you the full roadmap.
Let’s get started.
Most date pickers follow a similar user interaction pattern. That means you can build a reusable logic flow to automate them using Selenium and Java.
Here’s a clear path to follow. It works across most web applications, no matter which datepicker library is used.
Start by launching your browser and navigating to the page that contains the datepicker widget. This is usually a booking form, a scheduling interface, or a date filter field.
Use Selenium to locate the input field or calendar icon that triggers the datepicker. You can click the element using WebDriver commands. This action usually reveals a calendar widget as an overlay or inline component.
Once the calendar is visible, look for the header that shows the current month and year. If your target date is not in the visible view, click the "next" or "previous" controls to navigate. Use Selenium's click and wait strategy to ensure smooth transitions between months.
Now that the correct month is displayed, locate the specific day cell. Most datepicker widgets render each day as a clickable element. Use a locator that targets the day label or a data-date attribute. Click the desired date to complete the selection.
This interaction sequence is the foundation for selecting dates in any datepicker using Selenium WebDriver. It’s adaptable to various UI libraries and can be extended for range pickers or dynamic calendars.
📌 Tip: Before you build your logic, inspect the datepicker HTML structure. Look for predictable attributes or class patterns that help you locate elements quickly.
Before you automate a datepicker in Selenium, you need a working Java test project. A clean setup saves time when building and debugging your test cases.
Start with a simple Maven project. You can use TestNG or JUnit 5 as your test runner. Create a basic structure with a BaseTest class that handles WebDriver setup, timeouts, and teardown logic. This helps you write cleaner tests for any datepicker scenario.
Once your environment is ready, run a quick test. Open a page, check the title, and close the browser. This confirms everything works before you interact with the datepicker in Selenium.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class BaseTest {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("https://katalon.com");
String title = driver.getTitle();
System.out.println("Page title is: " + title);
driver.quit();
}
}
Once this script runs successfully, your Selenium Java setup is ready. You can now begin automating any datepicker field confidently and without blockers.
Not all date pickers behave the same. Some are built using popular UI libraries. Others are custom components created in-house. Before you automate a datepicker in Selenium, it helps to know which type you are dealing with.
These are widely adopted by developers and often follow consistent structures in the DOM.
Each one has its own structure and interaction model. When building your test cases, you’ll want to inspect how the calendar renders on the page before selecting dates with Selenium.
Some calendars allow you to pick a single date. Others support range selection like "From" and "To". You may see the datepicker show inline inside the form or appear as a popover modal.
Many widgets have dropdowns or arrow buttons to switch months or years. Some restrict past or future dates using disabled styles. Others use ARIA attributes for accessibility. These behaviors affect how your locators and click logic should work in Selenium.
📌 Tip: A reliable way to identify the calendar type is to trigger it, right-click the visible calendar, and choose "Inspect". Start from there to plan your Selenium locators.
Locators are the foundation of any stable Selenium test. When working with a datepicker in Selenium, choosing the right locator strategy helps your tests stay resilient even when the UI evolves.
Always look for attributes that remain consistent across renders. These give you a dependable way to interact with calendar elements without breaking your automation flow.
If you’re capturing the locator manually, test it across different views and sessions. This ensures the strategy works reliably for the full range of test cases.
📌 Avoid overly complex or absolute XPaths that depend on sibling positions. These often break when the DOM shifts slightly.
Date pickers usually share a few common parts. Learning these patterns helps you design better locators and validate each component with ease.
Each of these elements can be targeted using CSS selectors or attribute-based locators. Build your automation logic around them and keep the structure flexible.
Some calendars render inside an iframe. This is common in booking portals and embedded forms. Before you interact with the datepicker, switch to the correct frame using Selenium’s context switching.
The example below shows how to detect and switch to the iframe before selecting dates. After the interaction, always switch back to the default content to continue with the rest of your test flow.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
WebDriver driver = ...;
// Switch to iframe
WebElement iframe = driver.findElement(By.cssSelector("iframe.datepicker-frame"));
driver.switchTo().frame(iframe);
// Now interact with calendar
driver.findElement(By.cssSelector("td[data-date='2025-09-30']")).click();
// Switch back to main page
driver.switchTo().defaultContent();
When testing any datepicker in Selenium, frame awareness and smart locators go hand in hand. Use both to build tests that remain stable as the UI evolves.
Let’s bring it all together with a working example. In this scenario, you’ll learn how to automate a real-world datepicker on the MakeMyTrip website using Selenium WebDriver and Java.
This example demonstrates how to open the site, launch the calendar, navigate to a specific month, and pick a target date. You’ll use clean methods and robust waits to make the flow reliable.
Breaking down your test into focused methods improves clarity and reusability. In this example, you’ll define the following:
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.List;
public class MakeMyTripDatePicker {
WebDriver driver;
WebDriverWait wait;
public MakeMyTripDatePicker(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
public void openCalendar() {
driver.get("https://www.makemytrip.com/");
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("label[for='departure']"))).click();
}
public String getVisibleMonth() {
WebElement monthLabel = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".DayPicker-Caption div")));
return monthLabel.getText();
}
public void goToMonth(String targetMonthYear) {
while (!getVisibleMonth().equals(targetMonthYear)) {
driver.findElement(By.cssSelector(".DayPicker-NavButton--next")).click();
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.cssSelector(".DayPicker-Caption div"), targetMonthYear));
}
}
public void pickDay(String day) {
List<WebElement> days = driver.findElements(By.cssSelector("div[aria-disabled='false'] p"));
for (WebElement d : days) {
if (d.getText().equals(day)) {
d.click();
break;
}
}
}
}
Below is a basic example of how to use the class above in a TestNG test case. This test opens MakeMyTrip, selects a specific date, and verifies that the field reflects the correct selection.
@Test
public void testSelectDateOnMakeMyTrip() {
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
MakeMyTripDatePicker picker = new MakeMyTripDatePicker(driver);
picker.openCalendar();
picker.goToMonth("December 2025");
picker.pickDay("30");
String selectedDate = driver.findElement(By.cssSelector("input[placeholder='Departure']")).getAttribute("value");
Assert.assertTrue(selectedDate.contains("30 Dec"));
driver.quit();
}
Using this structure, your Selenium test becomes readable and easy to extend. You can change the target date, integrate it into data-driven testing, or apply it to round-trip selections with minimal changes.
Once you select a date from the datepicker in Selenium, it’s important to verify that the interaction worked as expected. These checks help ensure that the application processed the selected date correctly across all parts of the UI.
The first and most visible check is the value inside the date input field. This should reflect the chosen date in the correct format. In many applications, this value also appears in a breadcrumb, summary box, or as part of a confirmation message.
You can also check hidden fields that store the selected date in a machine-readable format. These are often used during form submission, and confirming their values adds confidence to your test coverage.
📌 Tip: Always confirm that the selected date matches both the visual label and the backend format used in submission. This confirms full integration.
You can improve test quality by including a few defensive checks. These help confirm that your automation script only interacts with valid, visible, and selectable dates.
These validations ensure that your datepicker automation in Selenium is reliable. You’re not just simulating clicks. You’re verifying outcomes that matter for business workflows.
Even with a solid approach, working with a datepicker in Selenium can present unexpected behavior. These patterns are predictable once you learn how most modern date pickers function under the hood.
You can solve these issues using common Selenium patterns and robust locator logic. Add these to your workflow when automating any datepicker in Selenium.
📌 Tip: Handling dynamic content gracefully is part of building resilient test cases. These strategies help you maintain consistency when automating any datepicker with Selenium.