Instead for example "9/1/1996" I want my code to display "09/01/1996". I don't know how to describe my question more specific. Here is my code for the MyDate class:
public class MyDate {
private int year;
private int month;
private int day;
public MyDate(int y, int m, int d){
year = y;
month = m;
day = d;
System.out.printf("I'm born at: %s\n", this);
}
public String toString(){
return String.format("%d/%d/%d", year, month, day);
}
}
And here is my main method:
public class MyDateTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyDate birthday = new MyDate(31,12,1995);
}
}
p.s I know that there is a way with importing calendar, but I rather doing it this way.
According to your problem it seems you are using customized class for date. But you can use inbuilt java.util.Date
class for any kind of Date represent or compare. So you can use DateFormat
to display formatted date time. Consider the following example.
Date date = //code to get your date
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(date));
OUTPUT:
13/10/2015
Additionally you there you should specify the pattern for your DateFormat
. Use following table for date formatting characters.
If you are still need to use your magic MyDate
class
You can use System.out.printf
specified with leading zeros as follows.
System.out.printf("%02d/%02d/%04d", date, month, year);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With