javajava-8localdate

Get day of month from LocalDate with leading zero


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?


Solution

  • 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. Edit: This one gives you a two-digit day of month (01 through 31):

    private static final DateTimeFormatter dayOfMonthFormatter
            = DateTimeFormatter.ofPattern("dd");
    

    To use it with your birth date:

        LocalDate dateOfBirthday = LocalDate.of(2000, 1, 1);
        String twoDigitDayOfMonth = dateOfBirthday.format(dayOfMonthFormatter);
        System.out.println("Day of month: " + twoDigitDayOfMonth);
    

    Output is:

    Day of month: 01

    Original answer: 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