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(); } } }
LocalDateTime.now()returns aLocalDateTime(javadoc). Don't parse it.SimeplDateFormatandDateclasses. Mixing them in will bring you nothing but trouble and over-complication. (2) If you are interested in the date and not the time of day, useLocalDate, notLocalDateTime.