Mends.One

0 is added but not shown as two digit when converted to int

Date, Java, Printing, Integer

I want to add a 0 in front of a date if it is single digit. So I made a code:

public class Zero {

    /**
    * @param args
    */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String zero="0";
        Calendar cal = new GregorianCalendar();
        int day1 = cal.get(Calendar.DAY_OF_MONTH);
        String seven1=Integer.toString(day1);
        System.out.println(""+seven1);
        System.out.println(""+day1);
        String added=zero.concat(seven1);
        System.out.println(""+added);
        int change=Integer.parseInt(added);
        System.out.println(""+change);
    }

}

So when I print change it prints only 7 not 07. Actually I want to make the int 07 instead of 7. So what modification should be done to print 07?

NB- I did not mention the if-else checking for single-digit or multi-digit date intentionally as there is no problem with it!

1
M
Mistu4u
Jump to: Answer 1 Answer 2 Answer 3 Answer 4 Answer 5 Answer 6

Answers (6)

Use SimpleDateFormat for formatting a date.

Your pattern will be dd.

SimpleDateFormat sdf = new SimpleDateFormat("dd");
System.out.println(sdf.format(new Date()));
5
C
Christian Kuetbach

Try this using the SimpleDateFormat

System.out.println(new SimpleDateFormat("dd").format(new Date()));
1
K
Kumar Vivek Mitra
public String addZero(String input) {
    if(input.length() == 1)
        return "0" + input;
    return input;
}

That method will only add a zero to the begining of a string if it's 1 digit, so if you hand it "1", itll return "01", if you hand it "11", itll return "11". I think thats what you want.

0
A
Alex Coleman

Have you thought about using a SimpleDateFormat object? This will give you a high degree of control of the formatting. The text dd will provide you with a zero-padded day value.

0
C
codebox

A quick solution would be:

int change = Integer.parseInt(added);
if (change < 10) {
   System.out.println("0" + change);
} else {
   System.out.println(change);
}

However a better solution would be to use the NumberFormat class.

0
K
km1

Comments:

Mistu4u said:
I don't want to print only. I want to make the int as 07

Related Questions