How to select Today's date from DatePicker in Webdriver

5,865 views
Skip to first unread message

Ramesh P

unread,
Mar 3, 2016, 4:58:32 AM3/3/16
to webdriver
Hi,

In my application there is a date picker .
I want to select Current date, so that it will select everyday 
How can it possible?


darrell grainger

unread,
Mar 4, 2016, 10:00:24 PM3/4/16
to webdriver
There is no standard date picker. So how to do what you want depends on how the date picker was implemented.

Dheeraj Shandilya

unread,
Mar 4, 2016, 10:30:39 PM3/4/16
to webd...@googlegroups.com
Hi Ramesh 

Darrell is right. It depends on how date picker was implemented.

You should identify the date picker table/div by id (or xpath).
Inside this find all the dates and store it in a list say DateList.

Get today's date with the help of Date class. 
Convert the date in string format. Split the string and store date part in a variable.

Now start a for each loop for all values in DateList.
if today's date matches with nth list value click on nth Date. 


Please find below a sample code and modify it as per your requirement.

            String month;
   String todaysDate;
// Get today's date
   Date date = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

   // Convert the date in specific format
   String formattedDate = sdf.format(date);
   todaysDate = formattedDate.substring(0, formattedDate.indexOf("/"));

   // Identify the date table
       WebElement dateTable = driver.findElement(By dateTableLocator);

       // Get all cell in a list
       List<WebElement> columns = dateTable.findElements(By.xpath("//td/a"));  

       for (WebElement cell: columns){
           if (cell.getText().equals(todaysDate)){
        month = cell.findElement(By.xpath("/..")).getAttribute("class");
        if(!month.contains("OtherMonth")){
           cell.findElement(By.linkText(todaysDate)).click();
           break; 
        }
           }
       }

With Best Regards
Dheeraj
        

--
You received this message because you are subscribed to the Google Groups "webdriver" group.
To unsubscribe from this group and stop receiving emails from it, send an email to webdriver+...@googlegroups.com.
To post to this group, send email to webd...@googlegroups.com.
Visit this group at https://groups.google.com/group/webdriver.
For more options, visit https://groups.google.com/d/optout.

nikhil rao

unread,
Aug 7, 2016, 11:39:27 PM8/7/16
to webdriver
Please look at my code and it doesn't work.

//start the browser
        WebDriver driver = new FirefoxDriver();
        //Open the URL
        driver.get("https://www.redbus.in/");       
        //maximize the window
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        //click on the Date Picker
        Thread.sleep(10000);
        driver.findElement(By.xpath(".//*[@id='txtOnwardCalendar']")).click();
        //now find the xpath for the main table of Date picker
        String Date_Table = "//div[@id='rbcal_txtOnwardCalendar']/table[1]//td";
        //store elements i.e dates in a list
        WebElement Dates = driver.findElement(By.xpath(Date_Table));
        List<WebElement> columns = Dates.findElements(By.tagName("td"));
        //find the no of elements
       
        for ( WebElement cell : columns)
        {
            if (cell.getText().equals(31))
            {
                cell.findElement(By.xpath(".//*[@id='rbcal_txtOnwardCalendar']/table[1]/tbody//td[contains(text(),'31')]")).click();
                break;
            }           
        }
       
        /*
        //run a for loop to find the the specified element
        for ( int i=0; i<Date_nodes; i++)
        {
                String date_value = Dates.get(i).getText();
                if (date_value.equals(31))
                {
                    Dates.get(i).findElement(By.xpath("//div[@id='rbcal_txtOnwardCalendar']/table[1]//td[contains(text(),'31')]"));
                    break;
                }
        }*/
        System.out.println("Date is selected");
        //end of for loop
    }//end of function
}//end of class

darrell grainger

unread,
Aug 8, 2016, 9:15:00 AM8/8/16
to webdriver
Just some notes about the code, i.e. things which jump out to me as bad practices you should avoid:

  1. Set up the WebDriver instance before you start using it. The driver.manage calls can come before the driver.get call.
  2. WHY are you waiting 10 seconds? If you are attempt to debug something, don't put a sleep statement in. Set a breakpoint on the first findElement call then run to the breakpoint using Debug mode. If you actually need to wait for something, get into the habit of using WebDriverWait and not relying on sleep statements, EVER.
  3. Not really a problem but I prefer By.cssSelector("#txtOnwardCalendar") over an XPath. Cleaner, simpler to maintain and probably faster.
  4. It is not clear what your logic is. I would use more descriptive code. You want the code to be self-documenting. I should be able to read the code and know what you are doing. If I have to look at the website and step through your code to figure it out I'm in for trouble later. When the website change and I have to update the test, I won't have the old website to step through and it will probably take me a while to figure out what the code used to do.
  5. Calls to WebDriver are expensive. You want to figure out what you need, logically, then make as few calls to get it as possible. Looping through every cell until you find what you need could result in dozens, if not hundreds, of calls to the browser. Slow and expensive.
I'll look at the actual task you are attempting later... I have standup in 15 minutes and my tests have finished running. :)

darrell grainger

unread,
Aug 8, 2016, 11:25:49 AM8/8/16
to webdriver
I can see that the element with id='rbcal_txtOnwardCalendar' is the table with all the dates for a given month. This table is not visible until you click on the element with id='txtOnwardCalendar'. So the clicking of this second element is to open the calendar. The next few lines are getting all the dates from the calendar. However it looks like you are finding the first TD element then finding the TD elements underneath it. I think maybe you wanted to find the TR element and find the TD elements underneath it.

If you want to click on August 31st then find and click August 31st. There is no need for a loop. Stop and think about this. A call to find August 31st might take 2 seconds. A call to find each day will also take 2 seconds. Add to that the cost of see if the current cell is the value "31" might take 2 seconds. So your algorithm is going to take 31 * (2 + 2) seconds to find and click "31". That would be a total of  2 minutes. The algorithm I'm suggesting might take 2 seconds. My code will be shorter, easier to read, faster, easier to maintain. Just creating something which clicks the correct day should not be your goal. You want something which will fail-fast, is easy to maintain and does the test you are attempting to automate.

public void test47() {
driver.get("https://www.redbus.in/");
closeSignInModalDialog();
openOnwardCalendar();
String dayToClick = "31";
clickASpecificDayOnTheCurrentMonth(dayToClick);
String dayCurrentlySelected = getDayCurrentlySelected();
assert(dayCurrentlySelected.equals(dayToClick));
}

private String getDayCurrentlySelected() {
openOnwardCalendar();
WebElement currentDay = driver.findElement(By.cssSelector("#rbcal_txtOnwardCalendar .current.day"));
return currentDay.getText();
}

private void clickASpecificDayOnTheCurrentMonth(String dayToClick) {
By dayLocator = By.xpath("//*[@id='rbcal_txtOnwardCalendar']//td[text()='" + dayToClick + "']");
List<WebElement> specificDayFromOnwardCalendar = driver.findElements(dayLocator);
if(specificDayFromOnwardCalendar.size() == 1) {
specificDayFromOnwardCalendar.get(0).click();
} else {
fail("Could not click the day " + dayToClick + " on the calendar");
}
}

private void openOnwardCalendar() {
WebElement onwardCalendar = driver.findElement(By.cssSelector("#txtOnwardCalendar"));
wdw.until(ExpectedConditions.elementToBeClickable(onwardCalendar));
onwardCalendar.click();
}

private void closeSignInModalDialog() {
By signInDialogLocator = By.cssSelector(".modalCloseSmall");
WebElement signInDialog = driver.findElement(signInDialogLocator);
wdw.until(ExpectedConditions.visibilityOf(signInDialog));
signInDialog.click();
wdw.until(ExpectedConditions.invisibilityOfElementLocated(signInDialogLocator));
}
 
The driver variable is a WebDriver instance:

WebDriver driver = new FirefoxDriver();

The wdw variable would be:

WebDriverWait wdw = new WebDriverWait(driver, 10);

If you read the initial test method it is very clear what it is doing. I go to the website, close the modal dialog (not part of your original code but I needed to do that), open the calendar, click on the specific day you want to select. I've also written it in such a way that you can change which day you want to select. From a test purpose I might select day 28 because I know that day exists for every month but it depends on what you are trying to test here. You might also want to look into a better way to determine the day select is the day you wanted to select. The final assert statement here might be a little too tightly coupled to the implementation.


On Sunday, 7 August 2016 23:39:27 UTC-4, nikhil rao wrote:

SuperKevy

unread,
Aug 8, 2016, 5:03:56 PM8/8/16
to webdriver
Does the target field for the date picker allow you to enter text directly or are you specifically testing the date picker features.?

darrell grainger

unread,
Aug 9, 2016, 8:32:54 AM8/9/16
to webdriver
The input field for the date is a readonly field. The moment you select it, it opens the date picker and you must select a date from the calendar.
Reply all
Reply to author
Forward
0 new messages