How to select date from Datepicker in Selenium WebDriver with Java?
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:
- Set up your Selenium and Java environment properly
- Identify different types of date pickers (and how they behave)
- Choose the right locator strategy for calendar widgets
- Write clean, reliable code to select dates by typing, clicking, or JavaScript
- Validate that the right date was selected
- Handle edge cases like disabled dates, iframes, and dynamic DOM
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.
Steps to select date from datepicker with Selenium and Java
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.
1. Open the target webpage
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.
2. Click the datepicker input or icon
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.
3. Navigate to the correct month and year
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.
4. Select the target date
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.
Pre-requisites & environment setup (Selenium + Java)
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.
Required tools
- JDK 8 or above
- Maven or Gradle for dependency management
- Selenium WebDriver Java bindings
- An IDE like IntelliJ IDEA or Eclipse
- WebDriverManager to manage browser drivers like ChromeDriver and GeckoDriver
Project structure
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.
Sanity check: open page and assert title
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.
Understanding date pickers you’ll encounter
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.
Common libraries used for date pickers
These are widely adopted by developers and often follow consistent structures in the DOM.
- jQuery UI Datepicker – often used in older enterprise systems
- Bootstrap Datepicker – clean UI and common in admin dashboards
- Flatpickr – modern, lightweight, and flexible
- React-Datepicker – popular in SPAs using React
- MakeMyTrip-style calendars – highly dynamic with custom layout and flight logic
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.
Behavioral differences to watch for
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.
How to detect the type of date picker
- Open the date picker so it’s visible in the DOM.
- Use browser DevTools to inspect the element.
- Check if it’s an <input type="date"> (native) or a custom <div>-based calendar.
- See if the widget is inside an <iframe> and note the frame name or index.
- Look for “Next” / “Previous” buttons or month/year dropdowns for navigation.
- Identify unique class names, data attributes, or ARIA roles for stable locators.
- Click around and watch if the DOM re-renders (plan for waits if it does).
- Test if you can type a date directly into the field.
- Write down your findings (type, frame presence, navigation pattern) for your test script.
📌 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.
Locator strategies for calendars
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.
1. Start with stable locators
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.
- data-* attributes often signal intent and are ideal for targeting day cells or buttons
- ARIA roles such as "gridcell" or "button" can narrow your search scope within the widget
- Unique IDs and class names that appear across environments are also safe to use
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.
2. Recognize datepicker patterns
Date pickers usually share a few common parts. Learning these patterns helps you design better locators and validate each component with ease.
- Month and year headers help you confirm that the correct calendar view is visible
- Next and previous buttons are essential for navigating across months
- Day cells represent selectable dates and may use data attributes or labels
- Disabled cells are used to indicate unavailable dates, especially for past or restricted ranges
- Range pickers usually label start and end dates with unique styles or attributes
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.
3. Handle iframes correctly
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.
Code to select a given date on the MakeMyTrip website
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.
Reusable methods to simplify the logic
Breaking down your test into focused methods improves clarity and reusability. In this example, you’ll define the following:
- getVisibleMonth – reads the calendar’s current month label
- goToMonth – navigates to the desired month using the next button
- pickDay – clicks the target date from the calendar grid
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;
}
}
}
}
How to use it in your test
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.
Validation & assertions after selection
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.
Key values to assert
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.
- Read the input field using getAttribute("value")
- Check summary labels that mirror the input field visually
- Inspect hidden inputs with type="hidden" if the form stores the selection elsewhere
📌 Tip: Always confirm that the selected date matches both the visual label and the backend format used in submission. This confirms full integration.
Additional verification for robustness
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.
- Try clicking a disabled date and verify that it does not receive focus or trigger a change
- After navigation, confirm that the visible month matches the intended one
- Check that the selected date remains unchanged after a refresh or DOM update
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.
Common issues & how to fix them
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.
Where issues often appear
- The calendar overlay sometimes doesn’t appear right after clicking the input. Timing differences in rendering can delay visibility.
- If the calendar lives inside an iframe, you must switch context to interact with it.
- Some date pickers re-render the DOM when navigating between months. This can invalidate previously located elements and trigger stale element exceptions.
- Disabled dates can still be matched by locators. If clicked, they might not respond or can interfere with the selection logic.
- Some calendars place elements slightly outside the current viewport. These need to be scrolled into view before interaction.
Fixes that make the script stable
You can solve these issues using common Selenium patterns and robust locator logic. Add these to your workflow when automating any datepicker in Selenium.
- Use explicit waits like ExpectedConditions.visibilityOfElementLocated and elementToBeClickable before clicking or reading any UI element
- Switch to the correct iframe using driver.switchTo().frame(...) when the calendar is nested
- Always re-locate elements after any month navigation or page refresh to avoid stale references
- Use JavaScript to scroll calendar elements into view if they sit beyond the visible viewport
- Apply a retry mechanism with polling to account for dynamic rendering or brief network delays
📌 Tip: Handling dynamic content gracefully is part of building resilient test cases. These strategies help you maintain consistency when automating any datepicker with Selenium.
