简体   繁体   中英

How to find most recent date compare to current date?

I created a list for dates in certain format. In that list I'm adding elements from some HTML code. Also I get curent time in format same as in list.

List<WebElement> times = driver.findElements(By.tagName("time"));
String timeStamp = new SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH).format(Calendar.getInstance().getTime());

System.out.println(timeStamp);
for (WebElement element: times) {
        System.out.println(element.getText());
    }

Now, how to get most recent passed date and compare with current date, because I must count how mach days have been passed?

You can do as follows :

  • iterate over your elements
  • parse them to LocalDate (set the good pattern in the formatter )
  • keep only the ones in the past
  • get the max
  • print it

List<WebElement> times = driver.findElements(By.tagName("time"));

LocalDate now = LocalDate.now();

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);

LocalDate mostRecent = times.stream()
            .map(webE -> LocalDate.parse(webE.getText(), formatter))
            .filter(date -> date.isBefore(now))
            .max(Comparator.comparingLong(LocalDate::toEpochDay))
            .orElseThrow(IllegalAccessException::new);

System.out.println(mostRecent);

LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);

Try using TreeSet.floor() / TreeSet.ceiling().

https://www.tutorialspoint.com/java/util/treeset_floor.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM