Pkdrc
Pkdrc

Reputation: 55

date is greater than or less than current date in java using java8 functionality

I have a date like this :: String d1="27-May-2017"; I need to compare if this date is earlier than today or not. I have tried the below code but not able to parse LocalDateTime.now(). The below line is showing compilation error as it is getting parsed.

--> Date date2 = sdf.parse(LocalDateTime.now());

Can anyone plz suggest the correct way

package com.example.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
public class Main2 {

    
    public static void main(String[] args) {
        try{
       
            SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy");
            String d1="27-May-2017";
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(LocalDateTime.now());

           
            if(date1.after(date2)){
                System.out.println("Date1 is after Date2");
            }
          
            if(date1.before(date2)){
                System.out.println("Date1 is before Date2");
            }

           
            if(date1.equals(date2)){
                System.out.println("Date1 is equal Date2");
            }

            System.out.println();
        }
        catch(ParseException ex){
            ex.printStackTrace();
        }
    }


}

Upvotes: 1

Views: 5500

Answers (2)

deHaar
deHaar

Reputation: 18558

Exactly the same advice as in the answer given by @Thomas, just a different way of using that API:

Use java.time:

public static boolean isBeforeToday(String date) {
    return LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.ENGLISH))
                    .isBefore(LocalDate.now());
}

You can use this method like this:

public static void main(String[] args) {
    String d1 = "27-May-2017";
    String r = isBeforeToday(d1) ? " is " : " is not ";
    System.out.println(d1 + r + "before today");
}

and receive the result

27-May-2017 is before today

Upvotes: 1

Thomas
Thomas

Reputation: 88707

Don't use the old API e.g. SimpleDateFormat and java.util.Date but if possible use java.time all the way:

//note that you should pass a Locale to be sure the right one is used to parse the month name
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy", Locale.ENGLISH);
LocalDate date1 = LocalDate.parse("27-May-2017", formatter );
LocalDate date2 = LocalDate.now());    

if(date1.isAfter(date2)) {
  System.out.println("Date1 is after Date2");
}
...

Upvotes: 4

Related Questions