-1

Can I know how can convert one date format to another date format.

public static LocalDate localDateToAnotherLocalDate(String oldPattern, String newPattern, String input) {
    DateTimeFormatter oldFormat = DateTimeFormatter.ofPattern(oldPattern);
    DateTimeFormatter newFormat = DateTimeFormatter.ofPattern(newPattern);
    LocalDate localDate = LocalDate.parse(input, oldFormat);
    String output = localDate.format(newFormat);
    System.out.println();
    return getLocalDate(output, newPattern);
}

public static LocalDate getLocalDate(String date, String datePattern) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(datePattern);
    return LocalDate.parse(date, formatter);

}

@Test
void getLocalDateToAnotherLocalDateTest() {
    LocalDate localDate = DateUtil.localDateToAnotherLocalDate("yyyy-MM-dd", "dd-MM-yyyy", "2022-11-20");
    System.out.println("localDate" + localDate.toString());
    assertEquals("20-11-2022", localDate.toString());
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
bharathi
  • 6,019
  • 23
  • 90
  • 152

1 Answers1

1

A LocalDate object can only ever be printed in ISO8601 format (yyyy-MM-dd). In order to print the object in some other format, you need to format it and save the LocalDate as a string.