-3

I get date in a format like LocalDate dateOfBirthday = LocalDate.of(2000, 1, 1);.

I need to get the day of the month from that date. I using dateOfBirthday.getDayOfMonth() and it works and return 1, but I need to get 01.

How I can do it?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
robert0801
  • 140
  • 1
  • 12
  • No, I can get date LocalDate.of(2000, 1, 10); and it won't be work. – robert0801 Mar 10 '21 at 13:59
  • 2
    Does this answer your question? [Add leading zeroes to number in Java?](https://stackoverflow.com/questions/275711/add-leading-zeroes-to-number-in-java) – OH GOD SPIDERS Mar 10 '21 at 14:03
  • 4
    `1` from `getDayOfMonth()` is an integer, `01` would be a string. So you have to covert it – Benjamin M Mar 10 '21 at 14:03
  • @OHGODSPIDERS If that answers the question, then it is giving the wrong answer. Given a `LocalDate` we should not convert first to `int` and then to a zero-padded `String`. We have `DateTimeFormatter` for the purpose, which is not mentioned in the question you mention. The duplicate marking is rather harmful. – Ole V.V. Mar 13 '21 at 11:09

1 Answers1

11

As Benjamin M correctly stated in a comment, 01 would be a string (not an int). The correct way to convert a date to a string goes through a formatter. This one gives you a two-digit month — so 01 for January through 12 for December:

private static final DateTimeFormatter monthFormatter
        = DateTimeFormatter.ofPattern("MM");

To use it with your birth date:

    LocalDate dateOfBirthday = LocalDate.of(2000, 1, 1);
    String twoDigitMonth = dateOfBirthday.format(monthFormatter);
    System.out.println("Month: " + twoDigitMonth);

Output is:

Month: 01

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161