How to receive user date through Jtextfield, using Jodatime?

Asked

Viewed 407 times

1

I am unable to do the user input. I want the program to make the difference of days between today’s date and the date typed by the user. The program has more implementations but it’s just this part that isn’t working.

private JTextField dataVencimento;
dataVencimento = new JTextField(20)
container.add(dataVencimento);

...

DateTime hoje = new DateTime();
DateTime dataVencimento = new DateTime();

Days daysBetween = Days.daysBetween(dataVencimento, hoje);

JOptionPane.showMessageDialog(null, "Dias de diferença: " + daysBetween, 
                     "Atraso", JOptionPane.INFORMATION_MESSAGE);

2 answers

1


Try to make this account using LocalDate, parse the string with DateTimeFormatter:

  String strDate = "30/08/2016";
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
  LocalDate dataVencimento = LocalDate.parse(strDate, formatter);

  LocalDate dataHoje = LocalDate.now();

  long daysBetween = ChronoUnit.DAYS.between(dataHoje, dataVencimento);

  System.out.println(daysBetween);

The above code, if executed today(31/07/2016), will display 30. If negative, it is because the second date is less than the first date passed on DAYS.between.

See working on ideone.

References:

Java SE 8 Date and Time(oracle)

Calculate days between two Dates in Java 8

0

Thanks there diegofm, your answer was useful, although I have managed to solve otherwise, it was just a matter of logic same.

private JTextField dia;
private JTextField mes;
private JTextField ano;

container.add(new JLabel("Dia"));
container.add(dia);
container.add(new JLabel("Mês"));
container.add(mes);
container.add(new JLabel("Ano"));
container.add(ano);

...

int day = Integer.parseInt(dia.getText());
int month = Integer.parseInt(mes.getText());
int year = Integer.parseInt(ano.getText());

DateTime hoje = new DateTime();
DateTime dataVencimento = new DateTime(year, month, day, 0, 0);

Days diferenca = Days.daysBetween(dataVencimento, hoje);

What I did was create a variable for each part of the date, day, month, year, and convert to an integer and put the variable within the Datetime.

  • You can also use a JFormattedTextField, with a mask that allows only the date format, and using the method I suggested, I believe it is even better than having to use 3 components. You will have to validate the 3 to get to if some invalid value has been passed, or if the field is coming blank. With the component I mentioned, you do this only once. Another option is to use the component JCalendar, who already does it all for you.

  • It’s true, I need to validate each one, not to mention that it gets boring three entries instead of just one. Once again it was worth.

Browser other questions tagged

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