How to convert Date to integer in java?

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 think it's because in Date format there are bars and they are not directly converted to integer, but I do not know how to do this conversion.

    
asked by anonymous 15.09.2017 / 21:20

3 answers

1

I understand that you want a different format but in this answer the parameter in the creation of SimpleDateFormat does not contain bars (consequently the "date generated" also does not); try to create it like this:

SimpleDateFormat formatador = new SimpleDateFormat("ddMMyyyy");
    
15.09.2017 / 21:32
2

Maybe you do not want to turn the date into integer but get its value in milliseconds? If this is the case, you can do it as follows.

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

Or, if you really want 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 some of those solutions that you want.

    
15.09.2017 / 21:33
0

The dates in java 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. One 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)

    
15.09.2017 / 21:27