javadatejava-8comparedate-parsing

I want to compare string date (dd.MM.yyyy) to current date?


I have a String date coming in form of dd.MM.yyyy. I want to compare if its a future date (today+1 day)

I am trying to convert the string into date and getting current date from SimpleDateFormat but when trying to convert the string date I am getting the output in "EEE MMM dd HH:mm:ss zzz yyyy" format.

String profileUpdateChangeDate = "31.01.2023"
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        Date changeDate = sdf.parse(profileUpdateChangeDate);
        _log.info("changeDate===>>>"+changeDate);
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
        String str = formatter.format(date);
        _log.info("Currentdate-===>"+str);

How can I check if profileUpdateChangeDate is a future date?


Solution

  • You can compare the parsed date "changeDate" with the current date. If the "changeDate" is after the current date, then it is a future date.

    String profileUpdateChangeDate = "31.01.2023";
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    Date changeDate = sdf.parse(profileUpdateChangeDate);
    Date currentDate = new Date();
        
    if (changeDate.after(currentDate)) {
        System.out.println("profileUpdateChangeDate is a future date");
    } else {
        System.out.println("profileUpdateChangeDate is not a future date");
    }