Home > Enterprise >  How to format LocalDateTime yyyy-MM-dd HH:mm to dd-MM-yyyy HH:mm as String for a whole list of an ob
How to format LocalDateTime yyyy-MM-dd HH:mm to dd-MM-yyyy HH:mm as String for a whole list of an ob

Time:10-28

I am trying to solve a problem which seems to be tricky on which I got stuck. Could you help please?

In Spring Boot I have an object Holiday for national holidays persisted on a MySQL database. The object Holiday contains the following attributes:

(...)

@Column(name = "title")
private String HolidayTitle;

@Column(name = "date")
private String holidayDate;

@Column(name = "updated")
private LocalDateTime updated;

@Column(name = "country")
private String country;

(...)

But I am interested on the updated attribute, which is stored, for example, as 2021-10-26 20:54:48 in the database. I want to format it as dd-MM-yyyy HH:mm to Thymeleaf, but it consists of a list of Holiday objects with different attributes.

In controller, the list is being retrieved as the following:

@GetMapping("/getAllHolidays")
public String getAllHolidays(Model theModel) {
    List<Holiday> theHolidays = holidayService.findAll();
    theModel.addAttribute("holidays", theHolidays);
    return "holidays";
}

How to format only the attribute updated for all holiday objects in the list theHolidays by using DateTimeFormatter?

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");

Is it possible to achieve this by using Java stream?

CodePudding user response:

You can parse the dates using Java Stream like this:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");

List<String> formattedDates = theHolidays.stream()
      .map(Holiday::getUpdated)
      .map(formatter::format)
      .collect(Collectors.toList());

But if you're using thymeleaf, you can format your dates like this:

<tr th:each="holiday : ${holidays}">
  <td th:text="${#temporals.format(holiday.updated, 'dd-MM-yyyy HH:mm')}"></td>
</tr>
  • Related