How do I scan a Date type data?

Asked

Viewed 284 times

0

I want to read like this, but you don’t have the option I want;

public class Cliente {

Date dataNascimento;

}

Scanner e = new Scanner(System.in);
cliente.setDataNascimento(e.next);

I did it but it didn’t work:

System.out.println("Digite a Data");
String fechaComoTexto = e.nextLine();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse(fechaComoTexto);
funcionario.setDataNascimento(date);
  • There’s no way to read one Date directly. You have to read a string in some format (either dd/mm/yyyy, yyyy-mm-dd, or any other) and then convert to Date: https://answall.com/search?q=java+converter+string+date

  • I did so but it does not give System.out.println("Type Date"); String closeText = e.nextLine(); Simpledateformat sdf = new Simpledateformat("dd/MM/yyyy"); Date date = sdf.parse(closeText); funcio.setDataNascimento(date); System.out.println("Type Address"); funcionario.setEndereco(e. next(); System.out.println("Type Name"); funcionario.setNome(e. next());

2 answers

3


Cannot read the object Date using Scanner. Only String, BigInteger, BigDecimal and primitive types.

An alternative is to receive the date as String and convert for Date.

Example:

String data = "18/09/2019";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(data);

-2

public class Cliente {
    Date dataNascimento;
}

Scanner e = new Scanner(System.in);
cliente.setDataNascimento(e.next);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

So it would work

System.out.println("Digite a Data");
Date date = sdf.parse(sc.next());
funcionario.setDataNascimento(date);

Browser other questions tagged

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