package webelements; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Date; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class DatePickers { static WebDriver driver; public static void main(String[] args) { // Specify path to WebDriver: System.setProperty("webdriver.gecko.driver", "/snap/bin/geckodriver"); // Launch browser and navigate to test page: WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get("https://ramoncaballero.dev/sdet/selenium-webdriver/playgrounds/"); // Click on the 'Date Pickers' accordion item: driver.findElement(By.xpath("//button[contains(text(),'Date Pickers')]")).click(); // DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); LocalDate today = LocalDate.now(); String inputDateAsString = formatter.format(today); String inputDateAsStringInJavaScriptFormat = ""; // // HTML Date Picker // // JavaScript uses dates in format "yyyy-MM-dd" // We set the value of the HTML Date Picker input using JavascriptExecutor // So we need to convert the date from format "dd-MM-yyyy" into "yyyy-MM-dd" try { SimpleDateFormat inputDateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date inputDate = inputDateFormat.parse(inputDateAsString); SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd"); inputDateAsStringInJavaScriptFormat = outputDateFormat.format(inputDate); } catch (ParseException e) { e.printStackTrace(); } WebElement htmlDatePickerInput = driver.findElement(By.id("html-datepicker")); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].value='" + inputDateAsStringInJavaScriptFormat + "';", htmlDatePickerInput); // // This is commented out so you can actually see what happened in the web page: // driver.quit(); } }