Read date from webpage to Selenium java

Purushoth :

I am working on Selenium Java, I need to get the following date format without the time, as a string in selenium java to validate whether it is up to date with the published date. I used getText() method from the website by splitting from the time and date. Is there any other best ways rather than this solution!

enter image description here

Ole V.V. :

java.time

There’s a little challenge in the fact that the string on the website does not include year. One simple way to handle it is:

    ZoneId websiteTimeZone = ZoneId.of("America/Lower_Princes");
    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("dd-MMM HH:mm", Locale.ENGLISH);

    String stringFromWebsite = "06-Feb 06:37";

    MonthDay today = MonthDay.now(websiteTimeZone);
    MonthDay date = MonthDay.parse(stringFromWebsite, formatter);
    if (date.equals(today)) {
        System.out.println("It’s up to date");
    } else {
        System.out.println("It’s *NOT* up to date");
    }

When I ran today (March 5), the snippet printed:

It’s NOT up to date

A MonthDay is a month and day of month without year. The advantage of using this class is we don’t need concern ourselves with year. A possible drawback is we can’t compare two such objects determine which one is before or after the other one. Such a comparison would require knowing the year of each one.

We need to know the time zone that the website uses since it is never the same date everywhere on Earth. Please insert the correct one where I put America/Lower_Princes.

A more advanced solution might check if the date is a few days before or after today’s date and/or also look at the time.

Tutorial link: Oracle tutorial: Date Time explaining how to use java.time.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=26721&siteId=1