Home > Blockchain >  Problem comparing dates with if statement
Problem comparing dates with if statement

Time:07-13

I've got a problem comparing.

The second "if" is always fulfilled even if the second condition of the "if" is false.

First, I had to use Timestamp.valueOf so I could transform LocalDateTime to Date ("a" is a type of data "Date"). What i want to do is compare if the current time is greater than a predetermined time (a.getFinFecha()), if so, return 1. If the current time is greater or equal to the predetermined time (a.getFinFecha()) less seven days and is lower than the pretermined date, I want to return 2. Else (which means if the current time is lower than a.getFinFecha() and lower than a.getFinFecha() less 7 days) return 3. The object I'm passing is lower than the pretermined date less 7 days and it returns 2. Never returns 3.

if (java.sql.Timestamp.valueOf(LocalDateTime.now()).compareTo(a.getFinFecha()) > 0) {
            return 1;
        } else if (java.sql.Timestamp.valueOf(LocalDateTime.now()).getDate() >= (a.getFinFecha().getDate() - 7) && java.sql.Timestamp.valueOf(LocalDateTime.now()).compareTo(a.getFinFecha()) <= 0) {
            return 2;
        } else {
            return 3;
        }

CodePudding user response:

I had to use Timestamp.valueOf so I could transform LocalDateTime to Date

No, you hadn't and you shoudn't. Avoid using deprecated methods like getDate() and make use of the java.time API. The simplest solution could be to convert the Date returned by a.getFinFecha() to LocalDateTime and compare according to your requierments:

private int yourMethod() {
    Instant instant        = Instant.ofEpochMilli(a.getFinFecha().getTime());
    LocalDateTime finFecha = LocalDateTime.ofInstant(instant, ZoneOffset.UTC); // or use appropriate offset for your use case
    
    if (LocalDateTime.now().isAfter(finFecha)) {
        return 1;
    } else if (LocalDateTime.now().isAfter(finFecha.minusDays(7))) {
        return 2;
    } else {
        return 3;
    }
}
  • Related