Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 659
sbanerjee Avatar asked Aug 23 '14 05:08

sbanerjee


People also ask

How do I convert a date to an integer in java?

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.

Can we convert integer to string in java?

We can convert int to String in java using String.valueOf() and Integer.toString() methods. Alternatively, we can use String.format() method, string concatenation operator etc.

How do I convert a date from one format to another?

Convert date to different format with Format CellsSelect the dates you want to convert, right click to select Format Cells from context menu. 2. In the Format Cells dialog, under Number tab, select Date from Category list, and then select one format you want to convert to from the right section.


2 Answers

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

like image 169
Adi Avatar answered Oct 16 '22 23:10

Adi


It seems to me that you don't really have a number representing your date, you have a string of three numbers: year, month, and day. You can extract those values with some simple arithmetic.

Integer value = 19000101;
int year = value / 10000;
int month = (value % 10000) / 100;
int day = value % 100;
Date date = new GregorianCalendar(year, month, day).getTime();
like image 35
Alexis King Avatar answered Oct 16 '22 23:10

Alexis King