javadatetimejava-timelocaldatetimedatetime-comparison

How to compare system's current LocalDateTime with input String date and time


I am trying to compare the current system's time and date with an input String time and date. I am using LocalDateTime.now() to get the systems current time, and also using DateTimeFormatter to format it as dd-MM-yyyy HH:mm pattern

static DateTimeFormatter frmt = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
static LocalDateTime time = LocalDateTime.now();

Here is what I have:

System.out.print("Enter the Appointment new Date and Time as dd-mm-yyyy hh:mm : ");
String dateAndTime = input.nextLine();

if (//dateAndTime is before or equals the current system time)
{
    System.out.println("The new date and time should be after the current time");
}
else
{
    System.out.println("Appointment has been updated");
}

Solution

  • Assuming you have parsed the input to LocalDateTime you can do that as follows:

    if (parsedDateTime.isAfter(LocalDateTime.now())) {
        System.out.println("Appointment has been updated");
    } else {
        System.out.println("The new date and time should be after the current time");
    }
    

    Keep in mind that isAfter will return false if parsedDateTime and LocalDateTime.now() are exactly the same.