Shadi Ahmed
Shadi Ahmed

Reputation: 9

How to check the displayed date in Selenium with Java

I am trying to get the displayed date in the exact format to validate if it is in MM/dd/yyyy HH:mm. I tried :

element.getAttribute("value")

but that returns "yyyy-MM-ddTHH:mm" which actually is different than what is in UI.

Also when I use:

LocalDateTime currentDateTime = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("ddMMyyyy");
String date = dtf.format(currentDateTime);

works fine: screenshot

Upvotes: 0

Views: 2090

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79075

The data from the UI may have been converted into ISO-8601 format by the bootstrap library. Therefore, if you need to get the value in the MM/dd/yyyy HH:mm format, you can do so using a DateTimeFormatter.

Demo:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String input = "2021-06-01T04:05";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm", Locale.ENGLISH);
        String formatted = LocalDateTime.parse(input).format(formatter);
        System.out.println(formatted);
    }
}

Output:

06/01/2021 04:05

ONLINE DEMO

Learn more about the modern Date-Time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Upvotes: 1

Related Questions