Difference of dates with Legend in a Textfield

Asked

Viewed 458 times

-1

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

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

  • Are you using java8? Or do you need to use java7?

  • java 8 am using

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);
}

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

  • Good afternoon! I really wasn’t clear on my question! I wonder if after the action of a button I use it was possible to fill of a Textfield automatically.

  • @Lizy as I said in the reply, you didn’t make it clear what kind of textfield you were referring to and what kind of your application.

  • Jtextfield Java Swing - Text field

  • 1

    @Lizy responding in a short way: yes, it is possible. Just pass the Dates of the 2 fields to that method within actionperformed. I will edit the answer.

  • Obg @Diegof!!! I will test!!!

  • @Lizy worked out well?

  • yes obg @Diego F

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.