-4

I am doing a leave management program, when the user apply a leave, I need to make sure the from date matches the application days for example -7 for apply in advance. So, I need to use the system date to subtract the from date to get the days between the two dates. How to do so?

System.out.print("From date(YYYY-MM-DD): ");
this.fromDate = sc.nextLine();
        
LocalDate systemDate = LocalDate.now();
        
LocalDate date = LocalDate.parse(this.fromDate, DateTimeFormatter.ISO_LOCAL_DATE);

File filelvT = new File("./leaveType/" + this.leaveTypeID + ".txt");
        
try(BufferedReader bRlvT = new BufferedReader(new FileReader(filelvT))){
    String line = bRlvT.readLine();
    String[]value = line.split(";");

    //the value[4] is the application days recorded in the particular txt file          
    if( ? < value[4]){   //so what should I write in the ?
                
    }    //end if
            
}catch(IOException err){
    err.printStackTrace();
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Yeoh Joey
  • 1
  • 4
  • Have you taken a look which methods `LocalDate` has to offer? – f1sh Feb 21 '23 at 10:21
  • 2
    [`Duration#between(Temporal, Temporal)`](https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/time/Duration.html#between(java.time.temporal.Temporal,java.time.temporal.Temporal)) or [`Period#between(LocalDate, LocalDate)`](https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/time/Period.html#between(java.time.LocalDate,java.time.LocalDate)) or [`LocalDate#until(ChronoLocalDate)`](https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/time/LocalDate.html#until(java.time.chrono.ChronoLocalDate)) – Slaw Feb 21 '23 at 10:21

1 Answers1

1

ChronoUnit.DAYS.between(Temporal, Temporal) is a possibility…

… because LocalDate implements Temporal.

Example:

public static void main(String[] args) {
    // System date
    var systemDate = LocalDate.now();
    // some other date
    var otherDate = LocalDate.parse("2023-01-19");
    // get the difference in days
    var daysBetween = ChronoUnit.DAYS.between(otherDate, systemDate);
    // print the result
    System.out.println(
            String.format("Difference between %s and %s is %d days",
                          otherDate,
                          systemDate,
                          daysBetween
                  )
         );
}

Output:

Difference between 2023-01-19 and 2023-02-21 is 33 days

Make somehow sure to pass the chronologically smaller LocalDate as first parameter, otherwise your result might become negative. You could check if systemDate.isBefore(otherDate), for example.

deHaar
  • 17,687
  • 10
  • 38
  • 51