How to convert Date to whole in Java?

Asked

Viewed 3,370 times

1

When I use this code:

Date data = new Date();
SimpleDateFormat formatador = new SimpleDateFormat("dd/MM/yyyy");           
int dataAtual =  Integer.parseInt(formatador.format(data));
System.out.println(dataAtual);

This error appears:

Exception in thread "main" java.lang.NumberFormatException: For input string: "15/09/2017"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)

I believe it is because in Date format there are bars and they are not directly converted to whole, but I do not know how to make this conversion.

3 answers

2

Maybe what you want is not to turn the whole date, but to take its value in milliseconds? If that’s the case, you can do it this way.

//Cria nova data
Date d = new Date();
//Printa o valor da data em millissegundos..
System.out.println(d.getTime());

Or, If Voce really wants to convert the 'date' into integer type 06/03/2017 to 06032017.. you can do something like this..

    SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
    System.out.println(Integer.parseInt(sdf.format(d)));

I hope it’s one of those solutions you want.

1


I understand you want a different format but in this answer the parameter in the creation of the SimpleDateFormat does not contain bars (hence the "generated date" does not); tries to create so:

SimpleDateFormat formatador = new SimpleDateFormat("ddMMyyyy");
  • my mistake was very silly ahahahah thank you

  • that nothing, error is error :P

0

Java dates are stored internally as the number of milliseconds since 1/1/1970 so the result is greater than the storage limit of type int, to solve this problem you must use a Long. A solution would be as follows:

int i = (int) (new Date().getTime()/1000);
System.out.println("Integer : " + i);
System.out.println("Long : "+ new Date().getTime());
System.out.println("Long date : " + new Date(new Date().getTime()));
System.out.println("Int Date : " + new Date(((long)i)*1000L));

Credits: Convert Current date as integer

Other references:

Learn about the new Java 8 Date API

Date (Java SE 8)

  • I have tested only the whole (which is what I want) and appears: 1505503917, but I need only the day, month and year, in that order, I can remove only that?

  • If your intention is to manipulate (add/subtract days) this will not work very well.

  • 1

    solved with the answers below. Thank you!!!

Browser other questions tagged

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