问题
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 ?
回答1:
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
回答2:
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();
回答3:
Try this:
String myDate= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date(19000101 * 1000L));
Assuming it is the time since 1/1/1970
EDIT:-
If you want to convert from YYYYMMDD to YYYY-MM-DD format
Date dt = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(String.ValueOf(19000101));
来源:https://stackoverflow.com/questions/25458832/how-can-i-convert-an-integer-e-g-19000101-to-java-util-date