For my exercise I have to calculate the difference (long duration) between the variables Instant inHour and Instant outHour .
In other words, I have to calculate the time that a person stayed in the parking to calculate the price.
This is the first time I use the Instant class, so I m a little bit lost :)
There is my class :
public class FareCalculatorService {
public void calculateFare(Ticket ticket){
if( (ticket.getOutTime() == null) || (ticket.getOutTime().isBefore(ticket.getInTime())) ){
throw new IllegalArgumentException("Out time provided is incorrect:"+ticket.getOutTime().toString());
}
Instant inHour = ticket.getInTime();
Instant outHour = ticket.getOutTime();
//TODO: Some tests are failing here. Need to check if this logic is correct
long duration = outHour - inHour;
switch (ticket.getParkingSpot().getParkingType()){
case CAR: {
ticket.setPrice(duration * Fare.CAR_RATE_PER_HOUR);
break;
}
case BIKE: {
ticket.setPrice(duration * Fare.BIKE_RATE_PER_HOUR);
break;
}
default: throw new IllegalArgumentException("Unkown Parking Type");
}
}
Thanks for helping.
You could use the method
public long until(Temporal endExclusive, TemporalUnit unit)inInstantclass."Calculates the amount of time until another instant in terms of the specified unit."
Documentation:
https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#until-java.time.temporal.Temporal-java.time.temporal.TemporalUnit-
Definitions on the second argument (
TemporalUnitunit) can be found in the classChronoUnit, which implements the interfaceTemporalUnit.Documentation:
https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ChronoUnit.html
So you need to calculate the time difference similar to that:
Just read a bit through the documentations of these 2 classes and it should be a easy task to implement it in your code.