Get day of month from LocalDate with leading zero [duplicate]

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

Browse More Popular Posts

Leave a Comment