Home > other >  How to format date webelement in Selenium JAVA?
How to format date webelement in Selenium JAVA?

Time:05-21

My webelement is a date 5/14/2022, I located the element using findElement() and stored as string in a variable using getText(). How can I format the date as mmddyyyy i.e 05142022? It should work even if my webelement date is in a format of 5/5/2022.

CodePudding user response:

One way you can do this conversion through Java, is by using two SimpleDateFormat objects, which will handle String values that have single character values for month and day.

    String dateInputString = "5/5/2022";
    SimpleDateFormat sdfIn = new SimpleDateFormat( "MM/dd/yyyy" );
    SimpleDateFormat sdfOut = new SimpleDateFormat( "MMddyyyy" );
        
    String output = sdfOut.format( sdfIn.parse( dateInputString ) );
    // output will be "05052022"

Also, since you are working with a string input and output, it may be tempting to just remove the separators and skip the date conversions, but this will not work correctly if you cannot ensure that the months and days are zero-filled. Hence, this is why its best to convert to date, otherwise the manual string manipulations to inject the needed zeros would become a little more complicated.

    String dateInputString = "5/5/2022"; 
    String output = dateInputString.replace("/",""); 
    // output will be "552022"
  • Related