How to Select a Date from DatePicker in Selenium [2021]

When you need to automate an airway, hotel, or similar website you need to deal with DatePicker or Calendar, and sometimes it is a little bit cumbersome to select a specific date on the Datepicker or calendar.  In this post, I will explain to you how to deal with Date Pickers in Selenium projects. Let’s start to learn this with examples. 

DatePicker in Selenium Example 1

I want to explain it with a scenario on Turkish Airlines website.

Note: Because of the Webdriver Bot Detection this test cannot be run properly but you can learn the approach. In debug mode, I run the test successfully and it worked.

Go to https://www.turkishairlines.com/tr-tr/ website

driver.navigate().to("https://www.turkishairlines.com");

Click to “dateSelector

//Click and open the Date Picker
driver.findElement(By.id("dateSelector")).click();

datepicker in selenium

Wait for the Departure Date DatePicker.

//This is from date picker table
WebElement dateWidgetFrom = wait.until(
    ExpectedConditions.visibilityOfAllElementsLocatedBy(By.className("ui-datepicker-calendar"))).get(0);

datepicker departure

Get all DatePicker’s elements by getting all <td> tags inside the date picker.

//This are the columns of the from date picker table
List<WebElement> columns = dateWidgetFrom.findElements(By.tagName("td"));

calendar in selenium

Click the current day inside this DatePicker. For this and for the other date operations, I wrote a helper class as shown below.

DateUtil Class for Date Related Operations

import java.time.LocalDate;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import org.openqa.selenium.WebElement;

public class DateUtil {
    //Get The Current Day
    public static String getCurrentDay() {
        //Create a Calendar Object
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());

        //Get Current Day as a number
        int todayInt = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println("Today Int: " + todayInt + "\n");

        //Integer to String Conversion
        String todayStr = Integer.toString(todayInt);
        System.out.println("Today Str: " + todayStr + "\n");

        return todayStr;
    }

    //Get The Current Day plus days. You can change this method based on your needs.
    public static String getCurrentDayPlus(int days) {
        LocalDate currentDate = LocalDate.now();

        int dayOfWeekPlus = currentDate.getDayOfWeek().plus(days).getValue();
        return Integer.toString(dayOfWeekPlus);
    }

    //Click to given day
    public static void clickGivenDay(List<WebElement> elementList, String day) {
        //DatePicker is a table. Thus we can navigate to each cell
        //and if a cell matches with the current date then we will click it.
        /**Functional JAVA version of this method.*/
        elementList.stream()
            .filter(element -> element.getText().contains(day))
            .findFirst()
            .ifPresent(WebElement::click);

        /**Non-functional JAVA version of this method.*/
        //for (
        //    WebElement cell : elementList) {
        //    String cellText = cell.getText();
        //    if (cellText.contains(day)) {
        //        cell.click();
        //        break;
        //    }
        //}
    }
}

and inside the test code, we can click the today’s day like below way. (If you want you can click any day. Rather than the current day, you can simply send “18” for example for the 18th day of the month.)

DateUtil.clickGivenDay(columns, DateUtil.getCurrentDay()); 

Then, I put a wait for 5 seconds to see the results. Because of bot-detection the webdriver cannot automate the site but in debug mode, by changing the user-agent I could run this scenario and it worked well.

DatePicker in Selenium Example 1 Code

import java.util.List;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class DatePickerTestsTurkishAirlines extends BaseTest {

    @Test
    @SneakyThrows
    public void turkishAirlinesDatePicker() {
        //Because of the Webdriver Bot Detection this test cannot be run properly.
        //But you can follow the approach in debug mode I run the test successfully and it worked.
        driver.navigate().to("https://www.turkishairlines.com");

        //Click and open the Date Picker
        driver.findElement(By.id("dateSelector")).click();

        //This is from date picker table
        WebElement dateWidgetFrom = wait.until(
            ExpectedConditions.visibilityOfAllElementsLocatedBy(By.className("ui-datepicker-calendar"))).get(0);

        //This are the columns of the from date picker table
        List<WebElement> columns = dateWidgetFrom.findElements(By.tagName("td"));

        DateUtil.clickGivenDay(columns, DateUtil.getCurrentDay());

        //Wait a bit to see that we have selected the data properly.
        Thread.sleep(5000);
    }
}

Let’s do one more example but this time on the FlyDubai website.

Date Picker in Selenium Example 2

The second example is for www.flydubai.com

Go to the website.

//Go to website
driver.get("https://www.flydubai.com/en/");

Click the departure place.

//Click Departure Place
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".airportPickerTo.makeBookingTo.mat-form-group"))).click();

//Wait Dropdown and click the first city
wait.until(ExpectedConditions.visibilityOfElementLocated(
    By.cssSelector(" .makeBookingTo .search-list-dropdown [data-metro-active='false']:nth-of-type(1)"))).click();

We wait for the DatePicker until it opens.

how to automate date picker in selenium

//Wait the DatePicker Opens
wait.until(ExpectedConditions.visibilityOfElementLocated((By.cssSelector(".lightpick__inner"))));

For Departure, will get all day elements inside our Date Picker and save them as WebElement List.

selenium date picker java

//This are the cell of the from date picker table for departure. Get all elements.
List<WebElement> cellsOfDepartureDate = wait.until(
    ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("section:nth-of-type(1) > .lightpick__days > div")));

and we can click today’s day by using our DateUtil class as shown below.

//Click the today for Departure
DateUtil.clickGivenDay(cellsOfDepartureDate, DateUtil.getCurrentDay());

For Arrival, we will click the 4th day of the Arrival table. First, we will get the Arrival Date Picker day elements and then click the 4th one.

//This are the cell of the from date picker table for arrival. Get all elements.
List<WebElement> cellsOfArrivalDate = wait.until(
    ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector("section:nth-of-type(2) > .lightpick__days > div")));

//Click the 4th day (element).
cellsOfArrivalDate.get(4).click();

DatePicker / Calendar Selenium Example 2 Code

import java.util.List;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class DatePickerTestsFlyDubai extends BaseTest {

    @Test
    @SneakyThrows
    public void flyDubaiDatePicker() {
        //Go to website
        driver.get("https://www.flydubai.com/en/");

        //Click Departure Place
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".airportPickerTo.makeBookingTo.mat-form-group"))).click();

        //Wait Dropdown and click the first city
        wait.until(ExpectedConditions.visibilityOfElementLocated(
            By.cssSelector(" .makeBookingTo .search-list-dropdown [data-metro-active='false']:nth-of-type(1)"))).click();

        //Wait the DatePicker Opens
        wait.until(ExpectedConditions.visibilityOfElementLocated((By.cssSelector(".lightpick__inner"))));

        //This are the cell of the from date picker table for departure. Get all elements.
        List<WebElement> cellsOfDepartureDate = wait.until(
            ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("section:nth-of-type(1) > .lightpick__days > div")));

        //Click the today for Departure
        DateUtil.clickGivenDay(cellsOfDepartureDate, DateUtil.getCurrentDay());

        //This are the cell of the from date picker table for arrival. Get all elements.
        List<WebElement> cellsOfArrivalDate = wait.until(
            ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector("section:nth-of-type(2) > .lightpick__days > div")));

        //Click the 4th day (element).
        cellsOfArrivalDate.get(4).click();

        //Wait and see the selection.
        Thread.sleep(5000);
    }
}

Date Picker in Selenium Webdriver Example 3

The third example is for Trivago.com website. Our scenario is as follows:

Open trivago.com

//Go to Trivago.com
driver.navigate().to("https://www.trivago.com.tr/");

Write “Antalya” in the search bar and wait and click the first result.

 //Search a City
 WebElement searchText = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("querytext")));
 searchText.clear();
 searchText.sendKeys("Antalya");

//Wait and Click the First Results
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".ssg-suggestions>li:nth-of-type(1)"))).click();

Wait for visibility of Hotels and DatePicker.

//Wait for Visibility of DatePicker
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".two-month-calendar")));

Select the Start Date with a CSS selector. Here we should consider both workdays and weekends. Thus, I used the “OR” operation in CSS Selector by using the comma “,” operator. It works for both workdays and weekends.

//Select Start Date (Wait visibility then click the start date.)
wait.until(ExpectedConditions.visibilityOfElementLocated
    (By.cssSelector(
        ".cal-day.cal-is-weekend.cal-is-selectable.cal-is-range.cal-is-range-start," 
            + ".cal-day.cal-is-selectable.cal-is-range.cal-is-range-start"))).click();

Select the End Date with a CSS selector. Here we should consider both workdays and weekends. Thus, I used the “OR” operation in CSS Selector by using the comma “,” operator. It works for both workdays and weekends.

//Select End Date (Wait Visibility then click the end date)
wait.until(ExpectedConditions.visibilityOfElementLocated
    (By.cssSelector(
        ".cal-day.cal-is-weekend.cal-is-selectable.cal-is-range.cal-is-range-end,"
            + ".cal-day.cal-is-selectable.cal-is-range.cal-is-range-end"))).click();

And wait for 4 seconds for results. The aim is to show how to select dates on DatePicker.

//See the results with your eyes. :)
//From now on, you can do what you want.
Thread.sleep(4000);

DatePicker Selenium Example 3 Code

import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class DatePickerTestTrivago extends BaseTest {

    @Test
    @SneakyThrows
    public void trivagoDatePickerTest() {
        //Go to Trivago.com
        driver.navigate().to("https://www.trivago.com.tr/");

        //Search a Hotel
        WebElement searchText = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("querytext")));
        searchText.clear();
        searchText.sendKeys("Antalya");

        //Wait and Click the First Results
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".ssg-suggestions>li:nth-of-type(1)"))).click();

        //Wait for Visibility of Calendar / DatePicker
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".two-month-calendar")));

        //Select Start Date (Wait visibility then click the start date.)
        wait.until(ExpectedConditions.visibilityOfElementLocated
            (By.cssSelector(
                ".cal-day.cal-is-weekend.cal-is-selectable.cal-is-range.cal-is-range-start,.cal-day.cal-is-selectable.cal-is-range.cal-is-range-start"))).click();

        //Select End Date (Wait Visibility then click the end date)
        wait.until(ExpectedConditions.visibilityOfElementLocated
            (By.cssSelector(
                ".cal-day.cal-is-weekend.cal-is-selectable.cal-is-range.cal-is-range-end,.cal-day.cal-is-selectable.cal-is-range.cal-is-range-end"))).click();

        //See the results with your eyes. :)
        //From now on, you can do what you want.
        Thread.sleep(4000);
    }
}

GitHub Project

https://github.com/swtestacademy/date-picker-in-selenium

I hope you liked this article. Please, feel free to write your comments and ask your questions if you have. 

Thanks,
Onur Baskirt

33 thoughts on “How to Select a Date from DatePicker in Selenium [2021]”

  1. Thanks for this tutorial. I have a question. Why did you use “.” in your xpath expression? Usualy we use dot sign if we want to find webelement in another weblement.

    Reply
    • Selenium IDE usage is simple. Just add the extension to firefox and then do record and play. In this case, I did not try to use Selenium IDE and I don’t have any experience. Just try it and share us your experiences.

      Reply
  2. Hi, when I am running the getCurrentDay () method, its getting terminated. console is displying below message :

    Getday.getCurrentDay [TestNG]

    can you please tell me the possible reasons for this.

    Reply
    • You can get the time container element with this css: .xdsoft_datetimepicker.xdsoft_noselect.xdsoft_showweeks .xdsoft_time_variant

      Then you can get the all divs under that container.

      Then, you can reach any time by using for loop.

      Reply
  3. Hi,

    Could you please help me to locates the Departure and Arrival date in below sites

    https://www.flydubai.com/en/

    I tried with below options where as it is not working as im getting “Element is not currently visible and so may not be interacted with build info ”

    driver.findElement(By.id(“departureDate”)).click();
    driver.findElement(By.xpath(“.//div[@class=’date-picker init’]/div[@class=’col-6′]/div[@class=’calendar-container is-filled’]/input[@id=’return-date’]”)).click();
    driver.findElement(By.id(“departureDate”)).sendKeys(“29 Dec 17”);
    driver.findElement(By.xpath(“.//body/div[5]/div/table/tbody/tr[4]/td[5]/button”)).sendKeys(“29 Dec 17”);
    Thread.sleep(5000);

    Reply
    • Hi, you can find the solution below. I also added this to my article. I hope it helps.

      public void FlyDubaiDatePickerTest () throws InterruptedException {
      //Go to website
      driver.get(“https://www.flydubai.com/en/”);

      //*****Departure day selection started.
      //Click Departure Date
      driver.findElement(By.id(“departureDate”)).click();

      //Wait until departure table visible
      wait.until(ExpectedConditions.visibilityOf(driver.findElements(By.cssSelector(“.pika-table”)).get(0)));

      //Click departure day
      driver.findElements(By.cssSelector
      (“button[data-pika-year=’2017′][data-pika-month=’11’][data-pika-day=’22’]”)).get(0).click();
      //*****Departure day selection finished.

      //*****Return day selection started
      //Click Return Date
      driver.findElement(By.id(“return-date”)).click();

      //Wait until departure table visible
      wait.until(ExpectedConditions.visibilityOf(driver.findElements(By.cssSelector(“.pika-table”)).get(1)));

      //Click return day
      driver.findElements(By.cssSelector
      (“button[data-pika-year=’2017′][data-pika-month=’11’][data-pika-day=’29’]”)).get(1).click();
      //*****Return day selection finished.

      //Check the operation in 5 seconds
      Thread.sleep(5000);
      }

      Reply
  4. Hi,

    Could you please also provide me how do I select calendar dates using robot framework, I am having issues while selecting dates from calendar control.

    Thanks,

    Reply
  5. Hi,

    I am using Robot Framework and I am having issues while selecting dates. Our system is not be able to add current date when it’s already added. The system will display “The current date is already assigned”.

    Thanks

    Reply
  6. HI
    Thanks for the Post. i have a question, how can i automate Bootstrap 3 Inline Date time Picker using Selenium 3 Web driver.

    Reply
  7. Salam brother, in the start date and end date, I did not see where could chose a specific day.
    Thanks, your help is appreciated.

    Reply
    • Hi, you can get all elements of the date-picker and click one of them. I am sharing a sample code. I hope it helps.

      //Get all the elements in date-picker
      List firstDaySelectionList = findElements(
      By.cssSelector(“.ui-datepicker-group.ui-datepicker-group-last [data-handler=’selectDay’]”));
      //Click which day you want
      firstDaySelectionList.get(12).click();

      Reply
  8. Hi Onur,

    Your examples are very useful. I just want to know if one has to select future dates, say 12-March-2020 and 15-Apr-2020 then how to accomplish the task using selenium python.
    Scenario:-
    Open Expedia.com
    Select Flight Tab
    Select Round-Trip
    Select from ana to city
    Select the journey date between 12-March-2020 and 15-Apr-2020
    Submit

    Reply
  9. I have a scenario for calendar where the calendar loads a new HTML page and while selecting the date control goes to the calendar but after the date has been selected control doesn’t roll back to the page. Its an angular app.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.