How to get the difference in days between two JDateChooser objects

I would like to know the difference in days (excluding time).

These are my objects JDateChooser

:

JDateChooser dateChooser_in = new JDateChooser();
JDateChooser dateChooser_out = new JDateChooser();

      

At first I tried to convert it to Date

, but I don't know how to do it.

+3


source to share


2 answers


JDateChooser

has a method getDate

that returns a java.util.Date

. Once you've done that, it's just a matter of using the Java 8 Time API or JodaTime to calculate the difference

Java 8

LocalDateTime from = LocalDateTime.ofInstant(dateChooser_in.getDate().toInstant(), ZoneId.systemDefault());
LocalDateTime to = LocalDateTime.ofInstant(dateChooser_out.getDate().toInstant(), ZoneId.systemDefault());

Duration d = Duration.between(from, to);
System.out.println(d.toDays());

      



Joda time

LocalDate from = LocalDate.fromDateFields(dateChooser_in.getDate());
LocalDate to = LocalDate.fromDateFields(dateChooser_out.getDate());

System.out.println(Days.daysBetween(from, to).getDays());

      

+1


source


If you have two dates, the number of days can be calculated as:

Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime();
System.out.println ("Number of days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));

      



See the TimeUnit documentation for more information .

0


source







All Articles