Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date to Integer conversion in Java

Tags:

java

date

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

int inputDate=20121220;
like image 942
Vinay Kumar Chella Avatar asked Sep 25 '12 23:09

Vinay Kumar Chella


1 Answers

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();
like image 198
João Silva Avatar answered Sep 27 '22 16:09

João Silva