Convert date to integer in Java

I have an int variable with the following. How to convert it to a Date object and vice versa.

int inputDate=20121220;
+5
source share
1 answer

Convert the value to Stringand use SimpleDateFormatto parse it to an object Date:

int inputDate = 20121220;
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date date = df.parse(String.valueOf(inputDate));

The converse is similar, but instead parseuse formatand convert from the resulting Stringto Integer:

String s = date.format(date);
int output = Integer.valueOf(s);

An alternative is to use substringand manually analyze the presentation of Stringyour Integer, although I highly recommend you against :

Calendar cal = Calendar.getInstance();
String input = String.valueOf(inputDate);
cal.set(Calendar.YEAR, Integer.valueOf(input.substring(0, 4)));
cal.set(Calendar.MONTH, Integer.valueOf(input.substring(4, 6)) - 1);
cal.set(Calendar.DAY_OF_MONTH, Integer.valueOf(input.substring(6)));
Date date = cal.getTime();
+11
source

All Articles