1

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ariana
  • 27
  • 6
  • Does this answer your question? [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – zodiac508 May 19 '22 at 17:50
  • What did your search bring up? It would probably get you a good answer faster than waiting for one to be posted here. – Ole V.V. May 19 '22 at 19:02
  • 1
    In Java: `LocalDate.parse("5/14/2022", DateTimeFormatter.ofPattern("M/d/u")).format(DateTimeFormatter.ofPattern("MMdduuuu"))` – Ole V.V. May 19 '22 at 19:02
  • @OleV.V. Hours of search didnt work, hence posted here. It worked, Thanks a lot! – ariana May 19 '22 at 19:23

1 Answers1

0

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"
r Blue
  • 175
  • 1
  • 9
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. May 20 '22 at 06:22