Selenium JQuery Datepicker Example

JQuery Datepicker is widely used on web pages and it is totally free. This article will show you two examples of how to use Selenium Webdriver to automatically select date and time in JQuery Datepicker. All below examples will use ChromeDriver to implement the automated date selection. Because ChromeDriver is more stable and faster than others as I tested.

1. Example 1: Use JQuery UI Datepicker

  1. This example will use JQuery UI Datepicker to implement the Datepicker widget, you can click here to see the example page.
  2. Below are the steps to select a date to use selenium webdriver.
  3. Below java code can get the destination year, month, day, hour, and minute value.
    	public static int getDestYear(Date destDate)
    	{
    		Calendar destCalendar = Calendar.getInstance();
    		destCalendar.setTime(destDate);
    	
    		return destCalendar.get(Calendar.YEAR);
    	}
    	
    	public static int getDestMonth(Date destDate)
    	{
    		Calendar destCalendar = Calendar.getInstance();
    		destCalendar.setTime(destDate);
    	
    		return destCalendar.get(Calendar.MONTH);
    	}
    	
    	public static int getDestDay(Date destDate)
    	{
    		Calendar destCalendar = Calendar.getInstance();
    		destCalendar.setTime(destDate);
    	
    		int destDay = destCalendar.get(Calendar.DAY_OF_MONTH);
    		
    		return destDay;
    	}
    	
    	public static int getDestHour(Date destDate)
    	{
    		Calendar destCalendar = Calendar.getInstance();
    		destCalendar.setTime(destDate);
    	
    		return destCalendar.get(Calendar.HOUR_OF_DAY);
    	}
    	
    	public static int getDestMinute(Date destDate)
    	{
    		Calendar destCalendar = Calendar.getInstance();
    		destCalendar.setTime(destDate);
    	
    		return destCalendar.get(Calendar.MINUTE);
    	}
  4. Get the delta year and month between the current and the destination date time.
    	public static int getDeltaYear(Date destDate)
    	{
    		Calendar destCalendar = Calendar.getInstance();
    		destCalendar.setTime(destDate);
    		
    		int currYear = Calendar.getInstance().get(Calendar.YEAR);
    
    		int destYear = destCalendar.get(Calendar.YEAR);
    		
    		int ret = destYear - currYear;
    		
    		return ret;
    	}
    	
    	public static int getDeltaMonth(Date destDate)
    	{
    		Calendar destCalendar = Calendar.getInstance();
    		destCalendar.setTime(destDate);
    		
    		int currMonth = Calendar.getInstance().get(Calendar.MONTH);
    		
    		int destMonth = destCalendar.get(Calendar.MONTH);
    		
    		int ret = destMonth - currMonth;
    		
    		return ret;
    	}
  5. Find the calendar input text box by id. Scroll web page to it.
  6. Click or clear it to display the calendar.
  7. Click Prev or Next button to navigate to the target year or month.
  8. Because we can only click the Prev or Next button to change the month in this example, so we can click those buttons 12 times to change the year.
  9. Select day by XPath.
  10. Get the date in the JQuery Datepicker text box.
    	/* This method will pick date use JQuery Date widget.
    	 * */
    	public static void selectJQueryDate(WebDriver driver, String dateStr, String dateStrFormat) throws ParseException, InterruptedException
    	{
    		SimpleDateFormat sdSrc = new SimpleDateFormat(dateStrFormat);
    		Date destDate = sdSrc.parse(dateStr);
    		
    		int deltaYear = TestJQueryCalendar.getDeltaYear(destDate);
    		
    		int deltaMonth = TestJQueryCalendar.getDeltaMonth(destDate);
    		
    		int destYear = TestJQueryCalendar.getDestYear(destDate);
    		
    		int destMonth = TestJQueryCalendar.getDestMonth(destDate);
    		
    		int destDay = TestJQueryCalendar.getDestDay(destDate);
    		
    		String jqueryDatePage = "http://dev2qa.com/demo/datepicker/jquery-ui-1.12.1.custom/index.html";
    		
    		driver.get(jqueryDatePage);
    		
    		/* The wait object is used to wait for the Next or Prev button attached to DOM tree again after being clicked.
    		 * Because the re-attach time is uncertain, so we set a long time out value. 
    		 * */
    		WebDriverWait waitObj = new WebDriverWait(driver, 100);
    		
    		// Find the jquery datepicker.
    		By byDateInputTextBox = By.id("datepicker");
    		WebElement datePickerElement = driver.findElement(byDateInputTextBox);
    		
    		// First clear the text content in datepicker. This action will make the calendar displayed in the screen.
    		datePickerElement.clear();
    
    		// Scroll to the jquery datepiker section.
    		((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", datePickerElement);
    
    		// Get Next and Prev button's xpath.
    		String nextButtonXPath ="//*[@id=\"ui-datepicker-div\"]//a[@class=\"ui-datepicker-next ui-corner-all\"]";
    		String prevButtonXPath ="//*[@id=\"ui-datepicker-div\"]//a[@class=\"ui-datepicker-prev ui-corner-all\"]";
    		
    		// Change to target Year by click month Prev or Next navigation button.
    		TestJQueryCalendar.clickJQueryNextMonthButton(driver, waitObj, deltaYear*12, nextButtonXPath, prevButtonXPath);
    		System.out.println("Change calendar year to " + destYear + " complete.");
    		
    		// Change to target month.
    		TestJQueryCalendar.clickJQueryNextMonthButton(driver, waitObj, deltaMonth, nextButtonXPath, prevButtonXPath);
    		System.out.println("Change calendar month to " + destMonth + " complete.");
    		
    		Thread.sleep(1000);
    		
    		// Select day in the month.
    		By byDay = By.xpath("//*[@id=\"ui-datepicker-div\"]//a[contains(text(),'" + destDay + "')]");
    		WebElement dayElement = driver.findElement(byDay);
    		dayElement.click();
    		System.out.println("Change calendar day to " + destDay + " complete.");
    		
    		String text = datePickerElement.getAttribute("value");
    		System.out.println("Selected date is : " + text);
    	}
    
    	/* This method will click the Next or Prev month button deltaMonth times.
    	 * If deltaMonth > 0, then click Next button.
    	 * If deltaMonth < 0, then click Prev button.
    	 * */
    	public static void clickJQueryNextMonthButton(WebDriver driver, WebDriverWait waitObj, int deltaMonth, String nextButtonXPath, String prevButtonXPath) throws InterruptedException
    	{
    		// Destination month is bigger than current month, click Next month button.
    		if(deltaMonth > 0)
    		{
    			By byNext = By.xpath(nextButtonXPath);
    			
    			WebElement nextButton = driver.findElement(byNext);
    			Thread.sleep(1000);
    			for(int i=0;i<deltaMonth;i++)
    			{
    				nextButton.click();
    				
    				Thread.sleep(1000);
    
    				/* Wait for the web element to be presented until timeout. 
    				 * If this method throws NoSuchElementException, you can make the wait time out value more longer to try again.*/
    				waitObj.until(ExpectedConditions.presenceOfElementLocated(byNext));
    					
    				/*Because after click the Next button, the dom tree changed, so need to get Next button object again.*/
    				nextButton = driver.findElement(byNext);
    			}
    			
    		}
    		// Destination month is smaller than current month, click Prev month button.
    		else if(deltaMonth < 0)
    		{
    			By byPrev = By.xpath(prevButtonXPath);
    			
    			WebElement prevButton = driver.findElement(byPrev);
    			Thread.sleep(1000);
    			for(int i=0;i>deltaMonth;i--)
    			{
    				prevButton.click();
    				
    				Thread.sleep(1000);
    
    				/* Wait for the web element to be presented until timeout. 
    				 * If this method throws NoSuchElementException, you can make the wait time out value more longer to try again.*/
    				waitObj.until(ExpectedConditions.presenceOfElementLocated(byPrev));
    					
    				/*Because after click the Prev button, the dom tree changed, so need to get Prev button object again.*/
    				prevButton = driver.findElement(byPrev);
    			}
    		}
    	}

2. Example 2: Use JQuery Date Time Picker Widget.

  1. This example uses a JQuery plugin widget to implement the date-time calendar, you can click here to see the example page.
  2. Below are the steps to select the date and time using the selenium webdriver.
  3. Get destination year, month, day, hour, and minute value.
  4. Get the Datetimepicker input text box, clear it to display the calendar.
  5. Run javascript to scroll to it.
    	/* This method will test JQuery DateTime picker widget. */
    	public static void selectJQueryDateTimePicker(WebDriver driver, String dateStr, String dateStrFormat) throws ParseException, InterruptedException
    	{
    		SimpleDateFormat sdSrc = new SimpleDateFormat(dateStrFormat);
    		Date destDate = sdSrc.parse(dateStr);
    		
    		int destYear = TestJQueryCalendar.getDestYear(destDate);
    		
    		int destMonth = TestJQueryCalendar.getDestMonth(destDate);
    		
    		int destDay = TestJQueryCalendar.getDestDay(destDate);
    		
    		int destHour = TestJQueryCalendar.getDestHour(destDate);
    		
    		int destMinute = TestJQueryCalendar.getDestMinute(destDate);
    		
    		String jqueryDatePage = "http://dev2qa.com/demo/datepicker/datetimepicker-master/index.html";
    		
    		driver.get(jqueryDatePage);
    		
    		/* The wait object is used to wait for the Next or Prev button attached to DOM tree again after being clicked.
    		 * Because the re-attach time is uncertain, so we set a long time out value. 
    		 * */
    		WebDriverWait waitObj = new WebDriverWait(driver, 100);
    		
    		// Find the jquery datetimepicker.
    		By byDateInputTextBox = By.id("datetimepicker");
    		WebElement dateTimePickerElement = driver.findElement(byDateInputTextBox);
    		
    		// First clear the text content in datepicker. This action will make the calendar displayed in the screen.
    		dateTimePickerElement.clear();
    
    		// Scroll to the jquery datepiker section.
    		((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", dateTimePickerElement);
    		
    		// Select target year.
    		TestJQueryCalendar.selectJQueryDateTimePickerYear(driver, waitObj, destYear);
    		System.out.println("Change calendar year to " + destYear + " complete.");
    		
    		// Select target month.
    		TestJQueryCalendar.selectJQueryDateTimePickerMonth(driver, waitObj, destMonth);
    		System.out.println("Change calendar month to " + destMonth + " complete.");
    		
    		Thread.sleep(1000);
    
    		// Select target day.
    		TestJQueryCalendar.selectJQueryDateTimePickerDay(driver, waitObj, destDay);
    		System.out.println("Change calendar day to " + destDay + " complete.");
    		
    		// Select target hour and minute.
    		TestJQueryCalendar.selectJQueryDateTimePickerHourMinute(driver, waitObj, destHour, destMinute);
    		System.out.println("Change calendar time to " + destHour + ":" + destMinute + " complete.");
    		
    		String text = dateTimePickerElement.getAttribute("value");
    		System.out.println("Selected date is : " + text);
    	}
  6. Select destination year.
    	/* Select destination year in DateTimePicker year list.
    	 * */
    	public static void selectJQueryDateTimePickerYear(WebDriver driver, WebDriverWait waitObj, int destYear) throws InterruptedException
    	{
    		// First click default year item, then the year scroll list will be shown.
    		By defaultYearBy = By.xpath("//div[@class=\"xdsoft_label xdsoft_year\"]");
    		waitObj.until(ExpectedConditions.visibilityOfElementLocated(defaultYearBy));
    		WebElement defaultYearWebElement = driver.findElement(defaultYearBy);
    		defaultYearWebElement.click();
    		
    		// Select correct year in the list.
    		By byYearList = By.xpath("//div[@class=\"xdsoft_label xdsoft_year\"]//div[@class=\"xdsoft_option \"]");
    		List<WebElement> yearList = driver.findElements(byYearList);
    		for(WebElement yearElement : yearList)
    		{
    			String yearText = yearElement.getAttribute("data-value");
    			
    			if(String.valueOf(destYear).equals(yearText.trim()))
    			{
    				// Scroll to the year option web element to make it visible.
    				((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", yearElement);
    				
    				Thread.sleep(1000);
    				
    				// Click to select the year.
    				yearElement.click();
    				
    				break;
    			}
    		}	
    	}
  7. Select destination month.
    	/* Select destination month in DateTimePicker month list.
    	 * */
    	public static void selectJQueryDateTimePickerMonth(WebDriver driver, WebDriverWait waitObj, int destMonth) throws InterruptedException
    	{
    		// First click default month item, then the month scroll list will be shown.
    		By defaultMonthBy = By.xpath("//div[@class=\"xdsoft_label xdsoft_month\"]");
    		waitObj.until(ExpectedConditions.visibilityOfElementLocated(defaultMonthBy));
    		WebElement defaultMonthWebElement = driver.findElement(defaultMonthBy);
    		defaultMonthWebElement.click();
    		
    		// Select correct year in the list.
    		By byYearList = By.xpath("//div[@class=\"xdsoft_label xdsoft_month\"]//div[@class=\"xdsoft_option \"]");
    		List<WebElement> monthList = driver.findElements(byYearList);
    		for(WebElement monthElement : monthList)
    		{
    			String yearText = monthElement.getAttribute("data-value");
    			
    			if(String.valueOf(destMonth).equals(yearText.trim()))
    			{
    				// Scroll to the month option web element to make it visible.
    				((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", monthElement);
    				
    				Thread.sleep(1000);
    				
    				// Click to select the month.
    				monthElement.click();
    				
    				break;
    			}
    		}	
    	}
  8. Select destination day.
    	/* Select destination day in Month.*/
    	public static void selectJQueryDateTimePickerDay(WebDriver driver, WebDriverWait waitObj, int destDay)
    	{
    		// Get all day web element list.
    		By byDay = By.xpath("//div[@class=\"xdsoft_calendar\"]//td");
    		List<WebElement> dayElementList = driver.findElements(byDay);
    		
    		// Loop in the list.
    		for(WebElement dayElement : dayElementList)
    		{
    			// Get css class value first.
    			String classValue = dayElement.getAttribute("class");
    			
    			// If it is this month's day.
    			if(classValue.indexOf("xdsoft_other_month")==-1)
    			{
    				String dayValue = dayElement.getAttribute("data-date");
    				if(String.valueOf(destDay).equals(dayValue.trim()))
    				{
    					dayElement.click();
    					break;
    				}
    			}
    		}
    	}
  9. Select destination hour and minutes.
    	public static void selectJQueryDateTimePickerHourMinute(WebDriver driver, WebDriverWait waitObj, int destHour, int destMinute)
    	{
    		waitObj.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class=\"xdsoft_time_variant\"]")));
    		// Get all hour and minute web element list.
    		By byHourMinute = By.xpath("//div[@class=\"xdsoft_time \"]");
    	    List<WebElement> hourMinuteElementList = driver.findElements(byHourMinute);
    				
    		// Loop in the list.
    		for(WebElement hourMinuteElement : hourMinuteElementList)
    		{
    			// Get css class value first.
    			String classValue = hourMinuteElement.getAttribute("class");
    					
    			// If it is this month's day.
    			if(classValue.indexOf("xdsoft_time")>-1)
    			{
    				String hourValue = hourMinuteElement.getAttribute("data-hour");
    				String minuteValue = hourMinuteElement.getAttribute("data-minute");
    				
    				if(hourValue!=null && minuteValue!=null && hourValue.trim().length()>0 && minuteValue.trim().length()>0)
    				{
    					if(String.valueOf(destHour).equals(hourValue.trim()))
    					{
    						int minuteValueInt = Integer.parseInt(minuteValue);
    						int deltaMinute = destMinute - minuteValueInt;
    						if((deltaMinute <= 5) && (deltaMinute>=-5))
    						{
    							// Scroll to the hour:minute option web element to make it visible.
    							((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", hourMinuteElement);
    							
    							hourMinuteElement.click();
    							break;
    						}
    					}
    				}
    			}
    		}
    	}

3. Java Main Method To Test Above Example.

public static void main(String[] args) throws InterruptedException, ParseException {
		
	/* ChromeDriver is more stable and quick than Firefox Driver, so we use Chrome Driver in this example. */
		
	//Set string variable value to Chrome Driver executable file path.
	String chromeDriverPath = "C:\\Workspace\\dev2qa.com\\Lib\\chromedriver_win32\\chromedriver.exe";
	//Assign chromeDriverPath to system property "webdriver.chrome.driver"
	System.setProperty("webdriver.chrome.driver", chromeDriverPath);
	//Initiate a new instance
	ChromeDriver chromeDriver = new ChromeDriver();
		
        // Test example 1.
	TestJQueryCalendar.selectJQueryDate(chromeDriver, "2016/09/09", "yyyy/MM/dd");
		
	Thread.sleep(3000);
		
        // Test example 2.
	TestJQueryCalendar.selectJQueryDateTimePicker(chromeDriver, "2016/08/18 09:19", "yyyy/MM/dd hh:mm");
		
	Thread.sleep(3000);

	chromeDriver.close();

}

1 thought on “Selenium JQuery Datepicker Example”

Leave a Comment

Your email address will not be published. Required fields are marked *

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