Difference of dates with calendar in a TextField

-1

I'm developing a hotel system and would like to automate some features in the system.

I would like, when you select two dates being dataEntrada and dataSaida using Calendar, make the difference of days in a TextField named QdtDiaria automatically appear when choosing these dates. It would be possible?

    
asked by anonymous 28.04.2016 / 00:57

1 answer

1

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

    
28.04.2016 / 13:05