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();
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);
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"));
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.
//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.
//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

Onur Baskirt is a Software Engineering Leader with international experience in world-class companies. Now, he is a Software Engineering Lead at Emirates Airlines in Dubai.
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.
Hi Adam, I am using FirePath and it automatically puts “.” before XPATH expression and it is working. If you remove it, it will also work too. For difference I suggest you to read this article: http://www.bennadel.com/blog/2142-using-and-expressions-in-xpath-xml-search-directives-in-coldfusion.htm
Hi,
I am using selenium IDE to generate the cases. How can I do this using the IDE?
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.
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.
The code is written for JUnit maybe the reason of the problem is this.
Hi, in this url https://xdsoft.net/jqplugins/datetimepicker/ there is time as well. how to handle the time.
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.
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);
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);
}
Thank you so much for your help..Onur Baskirt
Regards,
Kripesh.K
You are welcome Kripesh.
Salam Alikoum brother,
How to run this code ?
Do you have this code in ruby ?
Thanks,
For Ruby I suggest elementalselenium website.
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,
Hello, I am not a RobotFramework expert but maybe this link will help you. https://stackoverflow.com/questions/45942808/robot-framework-need-date-from-jquery-widget-date-picker They suggest XPath for selecting dates. Also please check this one: https://stackoverflow.com/questions/46857410/how-do-i-use-press-keys-in-robot-framework-to-send-date-in-calender-popup-in-chr
Thanks for your quick response and the reference, this will help me for sure.
You are welcome. :)
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
HI
Thanks for the Post. i have a question, how can i automate Bootstrap 3 Inline Date time Picker using Selenium 3 Web driver.
Please send me a sample website and your question on that site’s datepicker.
Salam brother, in the start date and end date, I did not see where could chose a specific day.
Thanks, your help is appreciated.
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 firstDaySelectionList = findElements(
List
By.cssSelector(“.ui-datepicker-group.ui-datepicker-group-last [data-handler=’selectDay’]”));
//Click which day you want
firstDaySelectionList.get(12).click();
Hello,
trying to write script to test datepicker in expedia but i don’t see css tag in it.
Send me the link please I will try to check. You can use several techniques CSS, XPath, etc.
Where a download “FirePath”? i dont found
Firepath is dead. Better to use selocity.
https://chrome.google.com/webstore/detail/ranorex-selocity/ocgghcnnjekfpbmafindjmijdpopafoe?hl=en
https:/ranorex-selocity/
Hello sir,
How to write logic for selecting date which is 2 days latter from current date…
Please check below articles:
https://www.mkyong.com/java/java-how-to-add-days-to-current-date/
https://stackoverflow.com/questions/428918/how-can-i-increment-a-date-by-one-day-in-java
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
Thanks. Hi Jayashree, I am not a Phyton expert but maybe this link will help you.
https://www.programiz.com/python-programming/datetime
https://stackoverflow.com/questions/25120621/python-get-date-in-future-x-days-and-hours-left-to-date
First, calculate the dates with the right format then select a journey with those times. Good luck.
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.
I am not sure in that case you switch from one scope to another one. Maybe you are searching sth like this: https://stackoverflow.com/questions/36271826/switching-windows-and-focus-in-webdriver-with-non-angular-pages
or this: https://stackoverflow.com/questions/28511013/non-angular-page-opened-after-a-click
Hi Sir,
I want selenium in java code for this websites www. trip adsvisor.com.we have to code for followings,
international tour page,
package page,
transport booking page
return ticket
Hi for this you can use fiver or upwork.
how can i get basetest class
Hi ufuk project code is here: https://github.com/swtestacademy/date-picker-in-selenium
Hi Onur,
First of all thanks for your efficient efforts in the testing community, I appreciated it.
Unfortunately, I could not understand the concept of selecting a date picking. I have tried a lot of time on it but I could not figure out how to select Ryanair’s(https://www.ryanair.com/gb/en) departure and arrival dates.
Could you please help me with that?
Hi Ozge,
If I find some time, I will try to do date-picking operation for that website.
On that website the date picker CSS is like below.
.datepicker__calendar.datepicker__calendar–left > calendar-body > div:nth-of-type(2) > div:nth-of-type(10)
In this CSS the first div:nth-of-type is starting from 2 to 7, and the second div:nth-of-type is starting from 1 to 19. For the second one you can increase the index with 3 like 1,3,4,7,10,13,16,19. For the first one, 2,3,4,5,6,7.
First one is for row (week), second one is for column (day)
Hi
Thanks for the hard work of maintaining this page, am writing a selenium java test where there’s a calendar pop out using your DateUtil was perfect when it comes to Current day but I tried day minus 4 and it still returns the current day. This is what I have done
public static String getCurrentDayMinus(int days) {
LocalDate currentDate = LocalDate.now().minusDays(3);
int dayOfWeekMinus = currentDate.getDayOfWeek().minus(days).getValue();
return Integer.toString(dayOfWeekMinus);
}
public static void getCurrentDayMinus(List 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);
Please can you assist me with this
Thanks
Hi Onur,
i’m using python 3.10 and selenium 4.i did a lot of research to click on the first object in the ui-datepicker-group, but I couldn’t write the code. Can you help me?