Search code examples
selenium-webdrivertestng-eclipse

Assertion to compare Current time in Selenium Webdriver with Java


I am new to selenium and java.. I need to do a check, in which my app creates a move for a person from current time(as start time) to a custom time... And in my test scenario, I need to check whether the start time is equal to the current time at which that move was created. Below I have the piece of code in which I have manually given the current time in Assert.. But I can't change it each time during the test run.. Can anyone help me to get the current time in hh:mm am/pm format and compare with the start time and give pass or fail in my test output?

WebDriverWait wait = new WebDriverWait(driver, 60);
WebElement element1 = wait.until(
                            ExpectedConditions.visibilityOfElementLocated(
                              By.xpath("//*[@id='tabpanel-t0-2']/tpr-summary-page/ion-content/div[2]/div/div[2]/div/ion-card/ion-row[1]/ion-col/ion-row[2]")
                            )
                          );
String element = driver.findElement(
                          By.xpath("//*[@id='tabpanel-t0-2']/tpr-summary-page/ion-content/div[2]/div/div[2]/div[1]/ion-card/ion-row[1]/ion-col/ion-row[2]/div[1]/label[1]")
                       )
                       .getText();
Assert.assertTrue(element.contains("1:35"));

Solution

  • You can get the current time in the HH:mm format by using the java.util.Date() library.
    In your case, you can assert the value like:

    Assert.assertTrue(element.contains(new SimpleDateFormat("h:mm").format(new java.util.Date())));
    

    This will always assert the value with the current timestamp.