How can I convert an Integer (e.g 19000101 ) to java.util.Date?

sbanerjee picture sbanerjee · Aug 23, 2014 · Viewed 71.7k times · Source

Here's my code:

Integer value = 19000101 ;         

How can I convert the above Integer represented in YYYYMMDD format to YYYY-MM-DD format in java.util.Date ?

Answer

Adi picture Adi · Aug 23, 2014

First you have to parse your format into date object using formatter specified

Integer value = 19000101;
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse(value.toString());

Remember that Date has no format. It just represents specific instance in time in milliseconds starting from 1970-01-01. But if you want to format that date to your expected format, you can use another formatter.

SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd");
String formatedDate = newFormat.format(date);

Now your formatedDate String should contain string that represent date in format yyyy-MM-dd