Removing time constrain from a list of dates and times in java

Viewed 24

I have web table in which one of the columns has date and timestamp. I'm trying to achieve a list of only current dates, and also removing the timestamp from the same.

Here's the code I've written:

List<WebElement> colValues = new ArrayList<>();
colValues = driver.findElements(By.xpath("//table[@class='v-table-table']//tbody//tr//td[17]"));
List<String> strings = new ArrayList<String>();
String string2 = String.valueOf(new ArrayList<String>());
for(WebElement e : colValues)
{
    strings.add(e.getText());
    System.out.println("Strings"+strings);
    string2 = String.valueOf(strings.size());
    for(int i = 1; i<=10; i++)
    {
        
    }
}

List elements: [08/09/2022 06:44:09, 31/12/9999 00:00:00, 08/09/2022 06:40:17, 08/09/2022 06:37:48, 08/09/2022 04:52:42, 08/09/2022 04:49:36, 08/09/2022 06:07:56, 08/09/2022 05:08:55, 04/11/2019 22:02:35, 15/04/2019 13:13:55]

Expected: remove timestamps and retrieve only today's date in list

1 Answers

First, I suggest you educate the publisher of your data about the value of using only ISO 8601 standard formats when exchanging date-time values via text.

Also, educate the publisher about including an offset or time zone if the data is meant to represent a specific point on the timeline.

If changing to standard format is not an option, define a formatting pattern to fit your inputs.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" ) ;

Parse each input as a LocalDateTime object.

LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

Determine today’s date. Doing so requires a time zone. For any given moment, the date varies around the globe by time zone.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ; 
LocalDate today = LocalDate.now( z ) ;

Extract the date from each LocalDateTime, compare to today’s date.

if( ldt.toLocalDate().isEqual( today ) ) { … }

We can do the parsing and testing-for-today in a single statement using streams.

List < String > inputs = … ;
List < LocalDateTime > hits = 
    inputs
    .map(
        input -> LocalDateTime.parse( input , f )
    )
    .filter(
        ldt -> ldt.toLocalDate().isEqual( today )
    )
    .toList()
;
Related