Test Calendar on Real Devices & Browsers

Test Datepicker in Selenium to handle Calendar in real user conditions on real device cloud

Get Started free
Home Guide How to Select Date from Datepicker in Selenium Webdriver using Java

How to Select Date from Datepicker in Selenium Webdriver using Java

By Garima Tiwari, Senior Content Writer -

Selenium is a widely used automation testing tool used to ensure the seamless working of web applications in accordance with predetermined technical and business requirements. Using Selenium is a great way to comply with the growing demands made upon developers and testers – faster and more efficient release of new and updated features, ideally within a few weeks.

Selenium Webdriver, a major component of the Selenium Test Suite is a web framework that runs automated tests on websites to ensure all UI elements are functioning exactly as expected.

Among different UI elements, the Date is essential for certain websites. Datepickers are often included as UI elements to websites in which the user has to select a date as an input value. This makes it an important feature that needs to be tested for accurate functioning using Selenium.

This article will explore a test case demonstrating how to select a date from a datepicker in Selenium Webdriver using Java. The example uses the MakeMyTrip website to demonstrate this function. The date to be selected is “15-AUGUST-2020” on the departure datepicker displayed on the website home page.

Steps to select Date from Datepicker with Selenium and Java

  1. Find the XPath of the Datepicker element. For Chrome, right-click and inspect the given element to find its XPath.

    Datepicker in selenium example
    Datepicker on the MakeMyTrip Website

  2. To find XPath of a UI element in Firefox, right-click on the desired element, go to “Inspect Element” to open the inspector which will help identify the XPath of the desired element.

How to select date from datepicker in selenium webdriver using java
Finding XPath using Inspect Element for Google Chrome

Code to select a given date on the MakeMyTrip website

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait; 

import java.awt.AWTException;

import java.time.Duration;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class MakeMyTripDateTest  {

WebDriver driver;

WebDriverWait wait;

 

@BeforeMethod

public void openBrowser() throws InterruptedException {

     //Launch chrome browser and navigate to Make My Trip Site

     driver = new ChromeDriver();

     wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        driver.get("https://www.makemytrip.com/");

     driver.manage().window().maximize();

     Thread.sleep(3000);

}

 

@Test

public void tripDetails() throws InterruptedException, AWTException {

     // Close the modal dialog box if it appears 

     List<WebElement> closeModal = driver.findElements(By.cssSelector("span.commonModal__close"));

     if (closeModal.size() > 0) {

         closeModal.get(0).click();

     }

     try {

         WebElement dept = wait

                    .until(ExpectedConditions.elementToBeClickable(By.cssSelector("p[data-cy='departureDate']")));

         dept.click();

         Thread.sleep(2000);

         selectDate("June 2024", "8");

         Thread.sleep(3000);

         String selectedDate=driver.findElement(By.xpath("//p[@data-cy='departureDate']/span[1]")).getText();

         Assert.assertEquals(selectedDate, "8");

     } catch (Exception e) {

         e.printStackTrace();

     }



public void selectDate(String month_year, String day) throws InterruptedException {

     // For selecting month and year

     List<WebElement> months = driver.findElements(By.xpath("//div[@class='DayPicker-Caption']/div"));

     System.out.println("months count: " +months.size());

    

     for (int i = 0; i < months.size(); i++) {

         // Select date corresponding to the the month

         if (months.get(i).getText().equals(month_year)) {

             List<WebElement> days = driver.findElements(By.xpath("(//div[@class='DayPicker-Caption']/div)[" + i

                     + "+1]/..//following-sibling::div[@class='DayPicker-Body']//div[@class='DayPicker-Day']//p"));

             System.out.println("days count: " + days.size());

             for (int j = 0; j < days.size(); j++) {

                 if (days.get(j).getText().equals(day)) {

                     days.get(j).click();

                     break;

                 }

             }

         }

     }      

}

 

@AfterMethod

public void closeBrowser() {

      driver.quit();

}

}

As demonstrated, selecting a date from a datepicker on a website is easy enough using Selenium and Java. Run the code, evaluate the results and start applying the same process to websites with this particular functionality.

BrowserStack Automate Banner 1

How to handle Calendar in Selenium

Datepicker is the UI element that is used to generate a Calendar in web applications. Essential functions in a calendar require selecting a date or date range. The above section demonstrates how to automate calendar in Selenium using Java with the help of an example. You can follow the same steps for calendar automation in Selenium on any website.

As recommended, it is important to run Selenium tests on real browsers and devices. BrowserStack offers a cloud Selenium Grid of 3000+ real browsers and devices for testing purposes. Simply Sign up, choose the required device-browser-OS combination on BrowserStack Automate Dashboard, and start running Selenium Tests for free.

Run Calendar Automation in Selenium on Real Devices

How to run Selenium Date Picker Tests on Real Devices using BrowserStack

BrowserStack Automate allows you to perform Automated Cross Browser Testing across real browsers, desktop, and mobile devices, through the simple steps mentioned below:

Step: 1- Sign up on BrowserStack and create a free account. After successful account creation, you can view the Authentication and Security details under the Summary tab.

Step: 2- Navigate to the Capabilities Generator page to select from a comprehensive set of options.

Step: 3- Choose your desired combination of device-browser from thousands of available combinations and generate capabilities using Capabilities Generator. In the below example, Windows OS version 11 with Chrome browser version 124 are selected.

Capabilities Generator

Step: 4- In any java editor, create a Maven project and add Selenium Java and Java client dependencies.

<dependencies>

<dependency>

<groupId>org.seleniumhq.selenium</groupId>

<artifactId>selenium-java</artifactId>

<version>4.5.0</version>

</dependency>

 

<dependency>

<groupId>org.testng</groupId>

<artifactId>testng</artifactId>

<version>7.6.1</version>

<scope>compile</scope>

</dependency>

</dependencies>

Below program showcases how to select the date from date picker using MakeMyTrip website on Windows OS version 11 and on latest chrome version.

Here are the steps:

  1. Launch MakeMyTrip website.
  2. Select any future date from next month from the date picker.
  3. Assert that the date is selected.
import java.net.MalformedURLException;

import java.net.URL;

import java.time.Duration;

import java.util.HashMap;

import java.util.List;

 

import org.openqa.selenium.By;

import org.openqa.selenium.MutableCapabilities;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.Test;

 

public class DatePicker {

public static String username = "<username>";

public static String accesskey = "<access_key>";

public static final String URL = "https://" + username + ":" + accesskey + "@hub-cloud.browserstack.com/wd/hub";

WebDriver driver;

String url = "https://www.makemytrip.com/";

 

MutableCapabilities capabilities = new MutableCapabilities();

HashMap<String, Object> bstackOptions = new HashMap<String, Object>();

 

@BeforeTest

public void setUp() throws MalformedURLException {

        capabilities.setCapability("browserName", "Chrome");

     bstackOptions.put("os", "Windows");

        bstackOptions.put("osVersion", "11");

        bstackOptions.put("browserVersion", "latest");

        capabilities.setCapability("bstack:options", bstackOptions);

     driver = new RemoteWebDriver(new URL(URL), capabilities);

}

 

@Test

public void testDatePicker() throws InterruptedException {

     driver.get(url);

     driver.manage().window().maximize();

     Thread.sleep(5000);

     // Close the modal dialog box if it appears

     List<WebElement> closeModal = driver.findElements(By.cssSelector("span.commonModal__close"));

     if (closeModal.size() > 0) {

         closeModal.get(0).click();

     }

     try {

         WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

         WebElement dept = wait

                 .until(ExpectedConditions.elementToBeClickable(By.cssSelector("p[data-cy='departureDate']")));

         dept.click();

         Thread.sleep(2000);

         selectDate("June 2024", "8");

         Thread.sleep(3000);

         String selectedDate = driver.findElement(By.xpath("//p[@data-cy='departureDate']/span[1]")).getText();

         Assert.assertEquals(selectedDate, "8");

     } catch (Exception e) {

         e.printStackTrace();

     }

}

 

public void selectDate(String month_year, String day) throws InterruptedException {

     // For selecting month and year

     List<WebElement> months = driver.findElements(By.xpath("//div[@class='DayPicker-Caption']/div"));

     System.out.println("months count: " + months.size());

 

     for (int i = 0; i < months.size(); i++) {

         // Select date corresponding to the the month

         if (months.get(i).getText().equals(month_year)) {

             List<WebElement> days = driver.findElements(By.xpath("(//div[@class='DayPicker-Caption']/div)[" + i

                     + "+1]/..//following-sibling::div[@class='DayPicker-Body']//div[@class='DayPicker-Day']//p"));

             System.out.println("days count: " + days.size());

             for (int j = 0; j < days.size(); j++) {

                 if (days.get(j).getText().equals(day)) {

                     days.get(j).click();

                     break;

                 }

             }

         }

     }

}

 

@AfterMethod

public void closeBrowser() {

     // driver.quit();

}

}

After running the above programs, you can check the result on the Automate Dashboard page. You also get to see the execution video. You can have access to text, network, and other logs.

Video Logs in BrowserStack Automate

In short, all the environment details and desired capabilities are available for each run on the Automate dashboard page.

Text logs in BrowserStack Automate

Talk to an Expert

 Why use BrowserStack Automate for Selenium Tests?

Here are the reasons why you should choose BrowserStack Automate to run your Selenium Tests on Real Devices and Browsers:

  • Parallel Testing: BrowsersStack’s Automate product supports parallel testing by which one can easily test their app on a pool of combinations of device and browser types. This ultimately helps in reducing the execution time taken to run on different platforms and devices and therefore giving quick feedback of the application’s performance.
  • Real Devices and Browsers: It is always wiser to test the application on real devices and browsers to simulate a real user experience. Testing on real devices gives the actual confidence about the application performance. Functional testing and even non-functional testing such performance, load and security should be performed on real devices as testing on emulators may not give accurate results. With Automate one can test on any latest mobile device or web browser without the overhead of purchasing a physical device.
  • Dedicated Dashboard: Running Selenium testcases on Automate product, creates a report in a dashboard which can be referred to manage and monitor the automation testing activities. The dashboard provides an overview of the testing status as Pass/Fail/Pending with all the environment details such as device name, OS version, Platform, browser name, browser version, test execution time and duration, screenshots, etc. It also maintains a history of test executions.
  • Custom Reports with Artifacts: In Automate, custom reports can be generated to provide detailed and customized reports for the automated test execution. With this feature it allows to customize the structure and content of the report as per user’s need. It can include a vast range of test data such as test execution status, device and browser configurations, test duration, video recording, screenshots, etc.
  • Easy Integration with CI/CD Pipeline: BrowserStack’s Automate product can be seamlessly integrated with popular CI/CD tools such as Jenkins, TeamCity, TravisCI. With CI/CD in place, team can achieve faster delivery cycles with great confidence in the reliability, performance and compatibility of the application across different devices and platforms.
Tags
Automation Testing Selenium Selenium Webdriver

Featured Articles

How to find broken links in Selenium

How to handle Alerts and Popups in Selenium?

Test Selenium Datepicker on Real Devices

Run Selenium Date Picker Tests on Real Devices & Browsers