Two-digit date display - java

Instead, for example, "9/1/1996", I want my code to display "09/01/1996". I do not know how to describe my question in more detail. 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);
    }

}

ps I know there is a way to import the calendar, but I prefer to do it this way.

+4
source share
5 answers

For your problem, it seems like you are using a personalized class for the date. But you can use the built-in class java.util.Datefor any kind of date representation or comparison. So you can use DateFormatto display formatted 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

, DateFormat. .

enter image description here

MyDate

System.out.printf, , .

System.out.printf("%02d/%02d/%04d", date, month, year);
+3
String.format("%d/%02d/%02d", year, month,  day)

.

+1

import java.text.SimpleDateFormat; import java.text.DateFormat;

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    System.out.println(dateFormat.format(date)); 
+1

String.format :

return String.format("%d/%02d/%02d", year, month,  day);
  • 0 ,
  • 2 , 2 ( ).
  • , 4 ( , 8 ).

ideone

+1

This is a matter of formatting numbers. Before "d" in% d you can put the length of the number field, and if you need leading zeros instead of leading spaces, then add "0" before that. So a field with a 2-digit number with leading zeros %02d.

So your code will look like this:

public String toString() {
    return String.format("%04d/%02d/%02d", year, month, day);
}
+1
source

Source: https://habr.com/ru/post/1611356/


All Articles