0

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161

2 Answers2

1

You could use the method public long until(Temporal endExclusive, TemporalUnit unit) in Instant class.

"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 (TemporalUnit unit) can be found in the class ChronoUnit, which implements the interface TemporalUnit.

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:

System.out.println(inHour.until(outHour, ChronoUnit.MINUTES)); 

Just read a bit through the documentations of these 2 classes and it should be a easy task to implement it in your code.

Dorian Feyerer
  • 258
  • 5
  • 14
1

This is already written for you. See class Duration. It has method between() that can take two Temporal instances (Instant for example) and your have the duration between them. After that you can get the duration in seconds or in hours or any other time units. See the method get() or getSeconds()

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36