How to omit 0 in a whole number Date string

102 views Asked by At

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;
    }
2

There are 2 answers

1
Andrew T. On BEST ANSWER

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

formatter = new SimpleDateFormat("M/d");
0
dipali On
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.