Date to Integer conversion in Java

前端 未结 1 987
死守一世寂寞
死守一世寂寞 2021-01-05 08:36

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

int inputDate=20121220;
相关标签:
1条回答
  • 2021-01-05 08:53

    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();
    
    0 讨论(0)
提交回复
热议问题