0

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;
    }
Compaq LE2202x
  • 2,030
  • 9
  • 45
  • 62

2 Answers2

2

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

formatter = new SimpleDateFormat("M/d");
Andrew T.
  • 4,701
  • 8
  • 43
  • 62
  • I was looking if there were other solutions, turned out this is similar to what I'm doing now. So I'll check this for the solution. Thanks. – Compaq LE2202x Dec 20 '13 at 08:25
1
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.

dipali
  • 10,966
  • 5
  • 25
  • 51