Search code examples
javanetbeansjdatechooser

Calculate Difference between two JDateChooser Value


This is my codes but this is not working.

    Start.getDate();
    End.getDate();
    int diffInDays = (int)( (Start.getDate() - End.getDate()) / (1000 * 60 * 60 * 24));
    System.out.println(diffInDays);

So how can i make a program that the user can view the difference between 2 JDateChooser.


Solution

  • Date/Time calculations are a complex subject which are typically is best solved using a dedicated library to solve.

    Java 8

    Instant start = Start.getDate().toInstance();
    Instant end = End.getDate().getInstance();
    
    Duration duration = Duration.between(start, end);
    

    Joda-Time

    If you can't use Java 8, then you should use Joda-Time instead

    DateTime start = new DateTime(Start.geDate().getTime());
    DateTime end = new DateTime(End.geDate().getTime());
    
    // You might need to use end, start instead, depending on which
    // is later
    Duration duration = new Duration(start, end);
    Period period = duration.toPeriod();
    

    You can have a look at this answer to see how you might format the value