Best way to receive "keyboard" date

Asked

Viewed 65 times

-1

Good morning, Galerinha.

I need to know how best to store java dates.

Example: In a customer class I need to receive the customer dataDNascization, but for that I need to receive this date from the keyboard. What’s the best way to do that?

  • 1

    Receiving data from separate MES DAY and YEAR would be a good way?

  • 1

    Welcome to Stackoverflow in English. I suggest you start by doing tour and read the guide to how to ask. Regarding your question she was not very clear. You speak in date but the goal is to use a java.util.date ? or java.sql.date ? or none of those ? And when it says save refers to a variable or database ?

2 answers

1

One way to do this is to receive day, month, year and use the data to set a Gregorian Calendar.

Example:

Scanner leitura = new Scanner(System.in); //Inicializa o leitor do teclado  

System.out.println("Digite o dia");  
int dia = leitura.nextInt(); // Ler do teclado e armazena na variavel dia   

System.out.println("Digite o mês"); 
int mes = leitura.nexInt; // Ler do teclado e armazena na variavel mês


System.out.println("Digite o ano"); 
int ano = leitura.nexInt;  // Ler do teclado e armazena na variavel ano 

GregorianCalendar dataDeNascimento = new GregorianCalendar();
dataDeNascimento.set(ano, mes-1, dia);  //Em GregorianCalendar os meses começam a partir do 0 e sim, ano é o primeiro a ser recebido.

There are other ways to do this such as using Date, but most of the methods are discontinued.

I usually do the way I showed above for you and depending on the operations you will do, Gregoriancalendar has many functionalities as for example get the date in Milliseconds and more...

If you want to read more: Devmedia - Javacalendar

  • 2

    Tip: use Localdate instead of Gregoriancalendar :)

  • 2

    Follow the @Dherik tip because GregorianCalendar can be affected by daylight savings and its value depends on the Timezone configured in the JVM. Now LocalDate do not have these problems (January is 1 in this API!) and is ideal if you only need the day, month and year. From Java 8, use java.time.LocalDate, and for JDK 6 and 7, there is the Threeten Backport, which has the same class, only in the package org.threeten.bp. Take a look at the oracle tutorial to see how the java.time works, is much greater than Calendar.

  • Interesting! Thanks for the tips even though the question is not mine!

0

Do you need to be from the keyboard? If not, you can use the Jdatepicker. If necessary, you can use "dd/mm/yyyy".

Scanner s = new Scanner();
String[] raw = s.next().split("/");
int dia = raw[0];
int mes = raw[1];
int ano = raw[2];

Browser other questions tagged

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