Try this way using the package classes java.time
:
public long subtrairData(Date dataEntrada, Date dataSaida) {
LocalDateTime LocalDataEntrada = dataEntrada.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
LocalDateTime LocalDataSaida = dataSaida.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
return ChronoUnit.DAYS.between(LocalDataEntrada, LocalDataSaida);
}
Running on IDEONE .
Note: read in this
answer (credits to @Math
by the link) a good explanation of why to use the classes of the java.time package to
compare dates, not the oldest native classes, such as Date
and
Calendar
.
UPDATE
And to fill a JTextField
with that difference inside a button action (as stated in the comments), you just have to call the method quoted inside the setText()
of your component, like this:
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
myJTextField.setText(String.valueOf(subtrairData(dataEntrada,dataSaida)));
}
});
Since the method returns, although it is in days, it is type long
, you need to convert to String
, using String.valueOf()
.
Note: You should validate the values of the date fields before passing them as parameters of the method above, so that empty or invalid dates do not arrive, thus avoiding throwing exceptions.
References:
Subtract dates in JAVA to take the difference of days
Calculate days between two dates in Java 8
Java 8: Calculate difference between two LocalDateTime
Convert java.util.Date to java.time.LocalDate