I have departure time - 02:00, arrival - 06:15, and on the way - "on the way 4h 15m". I want to calculate whether the travel time is counted correctly
HTML
<div class="wl-offer_edge-from">02:00</div>
<div class="wl-offer_duration">on the way 4h 15m</div></div>
<div class="wl-offer_edge-back">06:15</div>
My code JAVA+Selenide
But for some reason the test falls on "LocalTime timeDuration"
public void checkFlightDurationTime() {
SelenideElement card = $$(".wl").get(0);
LocalTime timeDeparture = LocalTime.parse(card.find(".wl-offer_edge-from").text(),
DateTimeFormatter.ofPattern("HH:mm"));
LocalTime timeArrival = LocalTime.parse(card.find(".wl-offer_edge-back").text(),
DateTimeFormatter.ofPattern("HH:mm"));
LocalTime timeDuration = LocalTime.parse($(".wl-offer_duration").text()
.replace("on the way ", "").replace("h ", ":").replace("m", ""));
PeriodFormatter hoursMinutesFormatter =
new PeriodFormatterBuilder().appendHours().appendSeparator(":")
.appendMinutes().toFormatter();
Period timeFrom = hoursMinutesFormatter
.parseMutablePeriod(String.valueOf(timeDeparture)).toPeriod();
Period timeOfDurationOriginal = hoursMinutesFormatter
.parseMutablePeriod(String.valueOf(timeDuration)).toPeriod();
Period timeBack = hoursMinutesFormatter.parseMutablePeriod(String.valueOf(timeArrival)).toPeriod();
Period timeOfDuration = Period.parse(timeBack.minus(timeFrom).toString(hoursMinutesFormatter));
if(timeOfDurationOriginal.equals(timeOfDuration)){
System.out.println("It's OK");
}}
DateTimeFormatterto parse the time 02:00 or 06:15 as they are already in the default pattern used byLocalTime. Note that the modern date-time API is based on ISO 8601.java.time.Durationfor your requirement. It was introduced with Java-8. If you are using Java-9, you can leverage some convenience methods that were introduced with this release.Demo:
Output:
Learn more about the the modern date-time API from Trail: Date Time.