Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying date in a double digit format - java

Tags:

java

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.

like image 782
Slender Man Avatar asked Feb 09 '23 20:02

Slender Man


1 Answers

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.

enter image description here

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);
like image 145
Channa Jayamuni Avatar answered Feb 19 '23 03:02

Channa Jayamuni