javalocaldatedatetimeformatter

Java - How to get the correct date format with LocalDate


I've been having trouble correctly formatting the date as dd-MM-YYYY.

When I arrange the String dateString in the order of year-month-day, or year-day-month, it allows the date to be formatted.

It seems to only work when the yearParsed String as at the begginning of dateString.

Attempting to use DateTimeFormatter.ofPattern("dd-MM-YYYY") didn't seem to affect the date so it looks like I was not using it correctly.

Could you please let me know what I am doing wrong?

The user inputs a day, month and year one at a time, and I am looking to output the date as: 01-12-2000. The if/else are there to add a '0' in front, if the date or month input is a single digit.

Any help would be greatly appreciated.

Thank you!

    String yearParsed = String.valueOf(year);
    String monthParsed;
    String dayParsed;
    if (dayString.length() == 1) {         
        dayParsed = "0" + String.valueOf(day); 
    }
    else {
        dayParsed = String.valueOf(day);
    }
    if (monthString.length() == 1) {         
        monthParsed = "0" + String.valueOf(month);        
    }
    else {
        monthParsed = String.valueOf(month);
    }
    
    String dateString = yearParsed + "-" + monthParsed + "-" + dayParsed;
    //String dateString = dayParsed + "-" + monthParsed + "-" + yearParsed;

    System.out.println("dateString " + dateString);
    
    LocalDate formattedDate = null;  
    DateTimeFormatter dateTimeFormatter;  
    dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
    //dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-YYYY");

    formattedDate = formattedDate.parse(String.format(dateString, dateTimeFormatter));
    System.out.println("Formatted Date = " + formattedDate);

Solution

  • Regarding your variable LocalDate formattedDate, you're misunderstanding the concept of formatted date.

    A formatted date is a String, because you can control it's format.

    When the object is a LocalDate instance, it contains value to determine a position in the time, when you just print it it has its default formatting, it you want one specific formatting you need a String representation of your date


    String year = "2021", dayString = "1", monthString = "3";
    
    LocalDate date = LocalDate.of(
            Integer.parseInt(year),
            Integer.parseInt(monthString),
            Integer.parseInt(dayString)
    );
    
    System.out.println(date); // 2021-03-01
    
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    String formattedDate = date.format(dtf);
    System.out.println("Formatted Date = " + formattedDate); // Formatted Date = 01-03-2021