How to select date from Datepicker in Selenium WebDriver with Java?

March 15, 2026 · 12 min read · Tool Comparison

Blog / Insights /
How to select date from Datepicker in Selenium WebDriver with Java?

How to select date from Datepicker in Selenium WebDriver with Java?

QA Consultant Updated on

Learn with AI

Linkedin

Facebook

X (Twitter)

Mail

Learn with AI

Selecting a date from a calendar contraption is one of the nigh mutual task in UI automation. And yet, it often become into a knavish challenge, especially when the datepicker behaves differently on each website.

Sometimes it 's a jQuery calendar, sometimes it 's a custom airline-style chooser, and in many cases, it perform n't answer good to direct input. If you 've e'er wrestled with a eccentric trial just to select one simple escort, you 're not alone.

This guide walks you through precisely how to deal adatepicker in Seleniumusing Java. You ’ ll learn how to:

  • Set up your Selenium and Java environment right
  • Identify different types of date chooser (and how they behave)
  • Choose the right locator scheme for calendar gubbins
  • Write clean, dependable codification to choose dates by type, tick, or JavaScript
  • Validate that the right date was selected
  • Handle edge cases like handicapped date, iframes, and dynamic DOM

We ’ ll besides walk through a real-world example from MakeMyTrip to exhibit how to automate appointment choice from a unrecorded travel calendar.

If you 're look to masterdate chooser mechanization in Selenium WebDriver with Java, this article will give you the entire roadmap.

Let ’ s get started.

Steps to choose date from datepicker with Selenium and Java

Most appointment picker follow a similar exploiter interaction pattern. That imply you can progress a reusable logic flow to automate them using Selenium and Java.

Here ’ s a clear path to follow. It works across most web coating, no matter which datepicker library is utilize.

1. Open the quarry 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 situate the input field or calendar icon that triggers the datepicker. You can click the constituent employ WebDriver command. This action usually reveals a calendar contrivance as an overlay or inline component.

3. Navigate to the correct month and twelvemonth

Once the calendar is visible, look for the cope that demo the current month and year. If your mark date is not in the visible view, snap the `` following '' or `` former '' control to navigate. Use Selenium 's click and wait strategy to control smooth transition between months.

4. Select the target date

Now that the correct month is display, locate the specific day cell. Most datepicker gizmo render each day as a clickable ingredient. Use a locater that targets the day label or adata-dateattribute. Click the desired date to finish the choice.

This interaction sequence is the foundation for selecting dates in anydatepicker using Selenium WebDriver. It ’ s adaptable to diverse UI libraries and can be extended for range selector or dynamic calendars.

📌 Tip: Before you progress your logic, inspect the datepicker HTML structure. Look for predictable attributes or class patterns that help you locate elements quickly.

Pre-requisites & amp; environment setup (Selenium + Java)

Before you automate a datepicker in Selenium, you need a working Java test project. A clean setup saves clip when building and debugging your test cases.

Required tools

  • JDK 8 or above
  • Maven or Gradle for dependency direction
  • Selenium WebDriver Java dressing
  • An IDE like IntelliJ IDEA or Eclipse
  • WebDriverManager to manage browser driver like ChromeDriver and GeckoDriver

Project structure

Start with a simple Maven project. You can use TestNG or JUnit 5 as your trial runner. Create a introductory construction with aBaseTestclass 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, see the title, and close the browser. This confirms everything deeds before you interact with the datepicker in Selenium.

Java
signification org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; importation io.github.bonigarcia.wdm.WebDriverManager; public class BaseTest {public motionless void primary (String [] args) {WebDriverManager.chromedriver () .setup (); WebDriver driver = new ChromeDriver (); driver.get (`` https: //katalon.com ''); String title = driver.getTitle (); System.out.println (`` Page rubric is: `` + title); driver.quit ();}}

Once this script runs successfully, your Selenium Java setup is ready. You can now start automating any datepicker field confidently and without blockers.

Understanding date pickers you ’ ll encounter

Not all escort pickers behave the same. Some are built apply popular UI library. 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 appointment chooser

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 mutual in admin dashboards
  • Flatpickr– modernistic, lightweight, and pliable
  • React-Datepicker– popular in SPAs using React
  • MakeMyTrip-style calendar– highly dynamic with usage layout and flying logic

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

Each one has its own structure and interaction model. When building your test example, you ’ ll want to inspect how the calendar render on the page before select dates with Selenium.

Behavioral departure to watch for

Some calendars permit 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 shift month or years. Some restrict past or future dates using disabled mode. Others use ARIA attributes for handiness. These behaviors affect how your locater and click logic should act in Selenium.

How to detect the type of date picker

  1. Open the date picker so it ’ s visible in the DOM.
  2. Use browser DevTools to scrutinise the element.
  3. Check if it ’ s an & lt; input type= '' date '' & gt; (native) or a custom & lt; div & gt; -based calendar.
  4. See if the contrivance is inside an & lt; iframe & gt; and note the shape name or indicant.
  5. Look for “ Next ” / “ Previous ” buttons or month/year dropdowns for pilotage.
  6. Identify unique family name, data attributes, or ARIA roles for stable locater.
  7. Click around and follow if the DOM re-renders (plan for delay if it does).
  8. Test if you can type a date direct into the battleground.
  9. Write down your findings (type, frame presence, navigation pattern) for your exam script.

📌 Tip: A reliable way to identify the calendar type is to trigger it, right-click the seeable calendar, and choose `` Inspect ''. Start from there to contrive your Selenium locators.

Locator strategies for calendars

Locators are the foundation of any stable Selenium exam. When working with a datepicker in Selenium, choosing the correct locater strategy help your tests stay lively even when the UI evolves.

1. Start with stable locater

Always seem for dimension that stay consistent across renders. These give you a true way to interact with calendar ingredient without breaking your automation flow.

  • data-*attributes often signal intent and are ideal for targeting day cell or buttons
  • ARIA rolessuch as `` gridcell '' or `` push '' can narrow your search scope within the widget
  • Unique IDsand category name that appear across environments are too safe to use

If you ’ re capturing the locator manually, test it across different views and sessions. This control the scheme work 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 figure helps you design best locators and formalise each ingredient with simpleness.

  • Month and year headershelp you substantiate that the correct calendar scene is visible
  • Next and previous buttonare essential for voyage across months
  • Day cellsrepresent selectable appointment and may use data attribute or labels
  • Disabled cellsare used to indicate unavailable dates, especially for past or restricted ranges
  • Range pickersusually label start and end dates with singular fashion or attributes

Each of these ingredient can be point apply CSS selectors or attribute-based locators. Build your automation logic around them and maintain the construction pliant.

3. Handle iframes correctly

Some calendar furnish inside an iframe. This is mutual in reserve portals and engraft forms. Before you interact with the datepicker, trade 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.

Java
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, flesh awareness and smart locators go hand in paw. Use both to build exam that continue stable as the UI evolves.

Code to select a give 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 demo how to open the situation, launch the calendar, navigate to a specific month, and pick a target date. You ’ ll use clean method and robust waits to make the flow reliable.

Reclaimable methods to simplify the logic

Breaking down your test into focused method amend lucidness and reusability. In this example, you ’ ll define the pursuit:

  • getVisibleMonth– reads the calendar ’ s current month label
  • goToMonth– navigates to the desired month using the next button
  • pickDay– clicks the target escort from the calendar grid
Java
meaning org.openqa.selenium. *; import org.openqa.selenium.support.ui.ExpectedConditions; significance 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 null 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 & lt; WebElement & gt; day = 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 canonic 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 battlefield reflects the correct selection.

Java
@ Test public void testSelectDateOnMakeMyTrip () {WebDriver driver = new ChromeDriver (); driver.manage () .window () .maximize (); MakeMyTripDatePicker selector = 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 construction, your Selenium test become clear and easy to extend. You can change the target date, integrate it into data-driven examination, or utilize it to round-trip selections with minimal alteration.

Validation & amp; assertions after selection

Once you select a date from the datepicker in Selenium, it ’ s significant to control that the interaction worked as expected. These checks facilitate control that the application treat the selected date correctly across all constituent of the UI.

Key values to avow

The first and most seeable check is the value inside the date input battlefield. 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 likewise check concealed fields that store the selected date in a machine-readable format. These are ofttimes used during form submission, and confirming their value adds confidence to your test reporting.

  • Read the input field usinggetAttribute (`` value '')
  • Check summary labels that mirror the input battleground visually
  • Inspect hidden input withtype= '' hidden ''if the form stores the pick elsewhere
📌 Tip: Always confirm that the selected date match both the visual label and the backend format used in submission. This confirms total integrating.

Additional verification for robustness

You can meliorate test quality by include a few justificative checks. These help confirm that your automation script only interacts with valid, visible, and selectable dates.

  • Try clicking a disabled appointment and control that it does not receive focusing or induction a alteration
  • After seafaring, confirm that the visible month matches the intended one
  • Check that the selected engagement stiff unaltered after a refresh or DOM update

These validations ensure that your datepicker automation in Selenium is dependable. You ’ re not only simulate clicks. You ’ re control outcomes that matter for line workflows.

Common issues & amp; 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 picker serve under the strong-armer.

Where issues often appear

  • The calendar overlay sometimes doesn ’ t seem right after clicking the input. Timing differences in rendering can detain visibility.
  • If the calendar inhabit inside an iframe, you must switch circumstance to interact with it.
  • Some date pickers re-render the DOM when navigating between months. This can invalidate previously site constituent and trigger stale component elision.
  • Disabled dates can still be matched by locators. If clicked, they might not answer or can interfere with the option logic.
  • Some calendar rate element slenderly outside the current viewport. These need to be scroll into view before interaction.

Fixes that make the script stable

You can solve these subject using common Selenium patterns and rich locater logic. Add these to your workflow when automating any datepicker in Selenium.

  • Use explicit waits likeExpectedConditions.visibilityOfElementLocated and elementToBeClickablebefore click or reading any UI element
  • Switch to the correct iframe usingdriver.switchTo () .frame (...)when the calendar is nest
  • Always re-locate elements after any month navigation or page refresh to deflect stale cite
  • Use JavaScript to scroll calendar factor into view if they sit beyond the visible viewport
  • Apply a retry mechanism with canvass to describe for dynamic rendering or abbreviated mesh delays
📌 Tip: Handling dynamical content graciously is component of building resilient test cases. These strategies help you maintain eubstance when automatise any datepicker with Selenium.
Explain

|

FAQs

Why are datepickers described as tricky to automatize in Selenium?

+

Because they deviate widely (jQuery/React/custom travel pickers), may not accept typewrite, can beflaky, and oft re-render the DOM or behave otherwise across sites. & nbsp;

What ’ s the distinctive step-by-step flow to select a date with Selenium + Java?

+

Open page → click input/icon →navigate month/yearvia next/prev or controls → locate the quarryday cell→ click to select. & nbsp;

What setup is recommended before automatise datepickers with Java?

+

A working Java trial project withJDK 8+, Maven/Gradle, Selenium WebDriver bindings, IDE, and oftenWebDriverManager, plus a base test structure (JUnit/TestNG) for setup/teardown. & nbsp;

What locator strategies are urge to keep datepicker test stable?

+

Prefer stable attributes likedata-* and ARIA function, avoid brittle absolute XPaths, re-locate factor after sailing to prevent stale references, and handleiframesby switching context first. & nbsp;

How should you corroborate the engagement selection and handle mutual edge causa?

+

Assert the input ’ svalue, optionally verify summary/hidden fields, handledisabled date, use explicit hold(visibility/clickability), and plan for DOM re-renders, scrolling, and iframe context.

Vincent N.
QA Consultant
Vincent Nguyen is a QA consultant with in-depth domain knowledge in QA, software testing, and DevOps. He has 5+ years of experience in craft substance that resonate with techie at all levels. His interests span from writing, technology, to building coolheaded material.

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free