Search code examples
androiddatesimpledateformatandroid-dateandroid-dateutils

Convert date into "17. December 2015" Format


I am getting date in form of "20150119" and I want to convert it into the format like: "19. January 2015" .

How can I convert date in such format.

I tried below code:

private void convertDate() {
        String m_date = "20150119";
        SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy.MM.dd");
        try {
            Date date = originalFormat.parse(m_date.toString());
            Log.e("Date is====", date.toLocaleString());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

But its giving me error:

java.text.ParseException: Unparseable date: "20150119" (at offset 8)


Solution

  • You will need to specify two formats: one to parse your input, one to format your output.

    1. The error occurs because the string you are trying to parse does not match the format you specified in originalFormat: that one needs to be

      SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
      

      if you want to parse strings of the format String m_date = "20150119";. Parsing a string with that format will give you a Date:

      Date date = originalFormat.parse(m_date);
      
    2. Then you may use another format to output your Date:

      SimpleDateFormat outputFormat = new SimpleDateFormat("dd. MMMM yyyy");
      System.out.println("Date: " + outputFormat.format(date));