Search code examples
javadatedate-comparison

Compare Dates Using JDateChooser


I have two boxes of JDateChooser and I would like to make the following comparison:

  • the user will inform the first date
  • when it finishes entering the second date, I make a comparison consisting of:
    • if the second date is greater than or equal to 11 days, the following message will appear:
JOptionPane.showMessageDialog (null,
    " Homologation Date Must Be Less or Equal to 11 Days Regarding Date of Shutdown ");

I made a code that compares, but even when the user puts a date below the condition he is showing the message.

The following code:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
dt1 = sdf.format(dcdataDeslig.getDate().getTime());
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
dt2 = sdf1.format(dchomolog.getDate().getTime());

if (dt2.compareTo(dt1) >= 11 ) {
    JOptionPane.showMessageDialog (null," Homologation Date Must Be Less or Equal to 11 Days Regarding       Date of Shutdown ");
    dchomolog.setDate(null);
    txtdataDisp.setText("");
    txtdataPg.setText("");
}
txtdataDisp.setText(dt2);
txtdataPg.setText(dt2);

Solution

  • When you call sdf.format, the result is a String. It's not a date, it's a text representing a date.

    And comparing strings won't give you the difference between 2 dates - string comparison will tell you if they are in alphabetical order, because strings represent a sequence of characters - a text - nothing more.

    As far as I could understand, dchomolog.getDate() returns a java.util.Date, so the getTime() method will return the numerical timestamp value, which is the number of milliseconds since Unix epoch.

    To calculate the difference between the dates, you can subtract the values of getTime(), resulting in a difference in milliseconds. Then you use a java.util.concurrent.TimeUnit to convert it to days:

    // get the difference in milliseconds
    long diffMillis = dchomolog.getDate().getTime() - dcdataDeslig.getDate().getTime();
    
    // transform to days
    long diffDays = TimeUnit.DAYS.convert(diffMillis, TimeUnit.MILLISECONDS);
    

    If the getDate() method returns a java.util.Calendar instead, just change the code to dchomolog.getDate().getTimeInMillis().

    Java 8 or higher

    If you have the java.time classes available, it's much easier - and also more reliable, as this API fixes lots of flaws from Date and Calendar.

    First you can convert your dates to Instant's and then use a ChronoUnit to calculate the difference in days:

    long diffDays = ChronoUnit.DAYS.between(dcdataDeslig.getDate().toInstant(), dchomolog.getDate().toInstant() ));