问题
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:
Use SimpleDateFormat for formatting a date.
Your pattern will be dd
.
SimpleDateFormat sdf = new SimpleDateFormat("dd");
System.out.println(sdf.format(new Date()));
回答2:
Try this using the SimpleDateFormat
System.out.println(new SimpleDateFormat("dd").format(new Date()));
回答3:
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.
回答4:
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.
回答5:
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.
回答6:
Try using http://docs.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html
the correct usage is something along the lines of
int day = Calendar.Day_OF_Month;
DecimalFormat df = new DecimalFormat("00");
System.out.println(df.format(day));
Also, dont forget that java months start at 0 :/
来源:https://stackoverflow.com/questions/11850609/0-is-added-but-not-shown-as-two-digit-when-converted-to-int