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

不打扰是莪最后的温柔 提交于 2019-11-29 10:20:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!