Search code examples
javajava-timeduration

Java LocalDateTime Duration fundamental


Here's my code:

// check if the time within 10 mins
if (Duration.between(listOfAppointment.get(Integer.parseInt(indicator) - 1).getDateTimeOfAppointment(), LocalDateTime.now()).compareTo(Duration.ofMinutes(10)) < 0) { 

    try {

        listOfAppointment.get(Integer.parseInt(indicator) - 1).setCheckIn(true);
        System.out.println("The check-in has been done! Let's see your PT!");
        break;

    } catch (Exception e) {

        System.out.println("Invalid input, please try again!");
        indicator = console.nextLine();
    }

} else {
    System.out.println("It seems that it's still too early, please wait util 10 minutes left!");
    break;
}

All related packages imported and I tried with sample date like one day after but still it always printed out the try-block content, please help me resolve it. Thanks!


Solution

  • updated answer - should swap the index of appointmentTime and now variables as below:

    int index = Integer.parseInt(indicator) - 1;
    
    LocalDateTime appointmentTime = listOfAppointment.get(index).getDateTimeOfAppointment();
    
    LocalDateTime now = LocalDateTime.now();
    
    Duration timeDifference = Duration.between(now, appointmentTime);
    
    if (timeDifference.compareTo(Duration.ofMinutes(10)) < 0) {
    
        listOfAppointment.get(index).setCheckIn(true);
        System.out.println("The check-in has been done! Let's see your PT!");
    } 
    
    else {
        
    System.out.println("It seems that it's still too early, please wait until 10 minutes are left!");
    
    }