I have an int variable with following. How can I convert it to Date object and vice versa.
int inputDate=20121220;
解决方案
Convert the value to a String and use SimpleDateFormat to parse it to a Date object:
int inputDate = 20121220;
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date date = df.parse(String.valueOf(inputDate));
The converse is similar, but instead of using parse, use format, and convert from the resulting String to an Integer:
String s = date.format(date);
int output = Integer.valueOf(s);
An alternative is to use substring and manually parse the String representation of your Integer, though I strongly advise you against this:
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();