Domanda

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;
    }
È stato utile?

Soluzione

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

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

Altri suggerimenti

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(System.currentTimeMillis());
                    String timer = formatter.format(calendar.getTime());
                    formatter.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
                    txtTimerCount.setText(formatter.format(timePassed));

i hope this is useful to you.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top