How to check if a date is in the future with Java

3 Answers

0 votes
import java.time.LocalDate;

public class Main {

    /**
     * Returns true if the specified date is after today.
     *
     * @param date the date to check
     * @return true if the date is in the future; otherwise false
     */
    public static boolean isFutureDate(LocalDate date) {
        return date.isAfter(LocalDate.now());
    }

    public static void main(String[] args) {

        // Example: tomorrow
        LocalDate futureDate = LocalDate.now().plusDays(1);

        if (isFutureDate(futureDate)) {
            System.out.println("The date is in the future.");
        } else {
            System.out.println("The date is not in the future.");
        }
    }
}


/*
run:

The date is in the future.

*/

 



answered 5 hours ago by avibootz
0 votes
import java.time.LocalDateTime;

public class Main {

    /**
     * Returns true if the specified date and time
     * occurs after the current date and time.
     */
    public static boolean isFutureDateTime(LocalDateTime dateTime) {
        return dateTime.isAfter(LocalDateTime.now());
    }

    public static void main(String[] args) {

        // Example: one hour from now
        LocalDateTime futureDateTime = LocalDateTime.now().plusHours(1);

        if (isFutureDateTime(futureDateTime)) {
            System.out.println("The date/time is in the future.");
        } else {
            System.out.println("The date/time is not in the future.");
        }
    }
}


/*
run:

The date/time is in the future.

*/

 



answered 4 hours ago by avibootz
0 votes
import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class Main {

    /**
     * Returns true if the specified instant
     * is after the current instant.
     */
    public static boolean isFutureInstant(Instant instant) {
        return instant.isAfter(Instant.now());
    }

    public static void main(String[] args) {

        // Example: 30 minutes in the future
        Instant futureInstant =
                Instant.now().plus(30, ChronoUnit.MINUTES);

        if (isFutureInstant(futureInstant)) {
            System.out.println("The timestamp is in the future.");
        } else {
            System.out.println("The timestamp is not in the future.");
        }
    }
}


/*
run:

The timestamp is in the future.

*/

 



answered 4 hours ago by avibootz
...