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);
}
Functioning in the IDEONE.
Note: read this article in this
reply(credits to @Math
by link) a good explanation of why to use the classes in the java.time package for
compare dates, not older native classes, such as Date
and
Calendar
.
UPDATE
And to fill a JTextField
with this difference within a button action (as stated in the comments), just make the call of the method cited within the setText()
of its component, thus:
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
myJTextField.setText(String.valueOf(subtrairData(dataEntrada,dataSaida)));
}
});
Like the return of the method, even though it’s in days, it’s like long
, you need to convert to String
, using String.valueOf()
.
Note: The values of the date fields must be validated before passing them as parameters of the above method, so that they do not arrive empty or invalid dates, thus avoiding the release of exceptions.
References:
Subtract JAVA dates from picking the days difference
Calculate days between two Dates in Java 8
Java 8: Calculate Difference between two Localdatetime
Convert java.util.Date to java.time.Localdate
Are you using java8? Or do you need to use java7?
– user28595
java 8 am using
– Lizy