[java] How to select the Date Picker In Selenium WebDriver

Currently working on Selenium WebDriver and using Java. I want to select values in date range from the drop down.. I want to know how can I select the values as Date, Month and year in the date picker drop down.

Here is the HTML tag:

<dd id="date-element">
<input id="fromDate" class="hasDatepicker" type="text" style="width:57px; padding:3px 1px; font-size:11px;" readonly="readonly" name="fromDate" value="01 Jan 2013">

<input id="toDate" class="hasDatepicker" type="text" style="width:57px; padding:3px 1px; font-size:11px;" readonly="readonly" name="toDate" value="31 Dec 2013">  

enter image description here

The below sample code i tried:

Log.info("Clicking on From daterange dropdown");
JavascriptExecutor executor8 = (JavascriptExecutor)driver;
executor8.executeScript("document.getElementById('fromDate').style.display='block';");
Select select8 = new Select(driver.findElement(By.id("fromDate")));
select8.selectByVisibleText("10 Jan 2013");
Thread.sleep(3000);

Log.info("Clicking on To daterange dropdown");
JavascriptExecutor executor10 = (JavascriptExecutor)driver;
executor10.executeScript("document.getElementById('toDate').style.display='block';");
Select select10 = new Select(driver.findElement(By.id("toDate")));
select10.selectByVisibleText("31 Dec 2013");
Thread.sleep(3000);

This question is related to java jquery selenium selenium-webdriver

The answer is


I think this could be done in a much simpler way:

  1. Find the locator for the Month (use Firebug/Firepath)
  2. This is probably a Select element, use Selenium to select Month
  3. Do the same for Year
  4. Click by linkText "31" or whatever date you want to click

So code would look something like this:

WebElement month = driver.findElement(month combo locator);
Select monthCombo = new Select(month);
monthCombo.selectByVisibleText("March");

WebElement year = driver.findElement(year combo locator);
Select yearCombo = new Select(year);
yearCombo.selectByVisibleText("2015");

driver.click(By.linkText("31"));

This won't work if the date picker dropdowns are not Select, but most of the ones I've seen are individual elements (select, links, etc.)


You can directly use following javascript

((JavascriptExecutor)driver).executeScript("document.getElementById('fromDate').setAttribute('value','10 Jan 2013')")

Do not inject javascript. That is a bad practice.

I would model the DatePicker as an element like textbox / select as shown below.

For the detailed answer - check here- http://www.testautomationguru.com/selenium-webdriver-automating-custom-controls-datepicker/

public class DatePicker {

    private static final String dateFormat = "dd MMM yyyy";

    @FindBy(css = "a.ui-datepicker-prev")
    private WebElement prev;

    @FindBy(css = "a.ui-datepicker-next")
    private WebElement next;

    @FindBy(css = "div.ui-datepicker-title")
    private WebElement curDate;

    @FindBy(css = "a.ui-state-default")
    private List < WebElement > dates;

    public void setDate(String date) {

        long diff = this.getDateDifferenceInMonths(date);
        int day = this.getDay(date);

        WebElement arrow = diff >= 0 ? next : prev;
        diff = Math.abs(diff);

        //click the arrows
        for (int i = 0; i < diff; i++)
            arrow.click();

        //select the date
        dates.stream()
            .filter(ele - > Integer.parseInt(ele.getText()) == day)
            .findFirst()
            .ifPresent(ele - > ele.click());

    }

    private int getDay(String date) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);
        LocalDate dpToDate = LocalDate.parse(date, dtf);
        return dpToDate.getDayOfMonth();
    }

    private long getDateDifferenceInMonths(String date) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);
        LocalDate dpCurDate = LocalDate.parse("01 " + this.getCurrentMonthFromDatePicker(), dtf);
        LocalDate dpToDate = LocalDate.parse(date, dtf);
        return YearMonth.from(dpCurDate).until(dpToDate, ChronoUnit.MONTHS);
    }

    private String getCurrentMonthFromDatePicker() {
        return this.curDate.getText();
    }

}

try to SendKeys instead of picking the date

driver.FindElement(yourBy).SendKeys(yourDateTime.ToString("ddd, dd.MM.yyyy",CultureInfo.CreateSpecificCulture("en-US")));

If it does not work, try to send native 'tab'

element.SendKeys(OpenQA.Selenium.Keys.Tab);

public String datePicker(String object,String data){
    APP_LOGS.debug("selecting date");
    try{

        WebElement dateWidget = driver.findElement(By.xpath(OR.getProperty(object)));

        List<WebElement> rows = dateWidget.findElements(By.tagName("tr"));  
        List<WebElement> columns = dateWidget.findElements(By.tagName("td"));  

        for (WebElement cell: columns){
            if (cell.getText().equals(data)){
                cell.findElement(By.linkText(data)).click();
                break; 
            }
        }
    }catch(Exception e){
        return Constants.KEYWORD_FAIL+" -- Not able to select the date"+e.getMessage();
    }
    return Constants.KEYWORD_PASS;
}

From Java 8 you can use this simple method for picking a random date from the date picker

List<WebElement> datePickerDays = driver.findElements(By.tagName("td"));
datePickerDays.stream().filter(e->e.getText().equals(whichDateYouWantToClick)).findFirst().get().click();

You can try this, see if it works for you.

Rather than choosing date from date picker, you can enable the date box using javascript & enter the required date, this would avoid excessive time required to traverse through all date elements till you reach one you require to select.

Code for from date

((JavascriptExecutor)driver).executeScript ("document.getElementById('fromDate').removeAttribute('readonly',0);"); // Enables the from date box

WebElement fromDateBox= driver.findElement(By.id("fromDate"));
fromDateBox.clear();
fromDateBox.sendKeys("8-Dec-2014"); //Enter date in required format

Code for to date

((JavascriptExecutor)driver).executeScript ("document.getElementById('toDate').removeAttribute('readonly',0);"); // Enables the from date box

WebElement toDateBox= driver.findElement(By.id("toDate"));
toDateBox.clear();
toDateBox.sendKeys("15-Dec-2014"); //Enter date in required format

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?

Examples related to selenium-webdriver

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Scrolling to element using webdriver? Only local connections are allowed Chrome and Selenium webdriver Check if element is clickable in Selenium Java