Search code examples
androiddatedatetimeandroid-dateandroid-dateutils

How to omit 0 in a whole number Date string


I have successfully changed the format of a date string from yyyy-MM-dd to MM/dd. Now the problem is that if the month and day values are less than 10 each, the format should be for example 2/7 and not 02/07. How do I do this?

Here's my code:

    public static String cahngeFormat(String dateTime) {
        Date date = null;
        String str = dateTime;
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = formatter.parse(str);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.HOUR, 2);
            formatter = new SimpleDateFormat("MM/dd");
            str = formatter.format(calendar.getTime());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

Solution

  • Change the format from "MM/dd" to "M/d" to allow single-digit output instead.

    formatter = new SimpleDateFormat("M/d");