简体   繁体   中英

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?

You should be using the new java.time classes, so:

    String profileUpdateChangeDate = "31.01.2023";
    DateTimeFormatter df = DateTimeFormatter.ofPattern("dd.MM.yyyy");
    LocalDate changeDate = LocalDate.parse(profileUpdateChangeDate, df);
    LocalDate date = LocalDate.now();
    System.out.printf("Is date %s in the future? %b%n", profileUpdateChangeDate, date.isBefore(changeDate));

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM