Post Page Advertisement [Top]



Click here to send WhatsApp On Unsaved Mobile Numbers For Free

How to format a date in a specific date format in a Thymeleaf Template in Spring Boot?

Example Code:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <title>Attendance List</title>
</head>
<body>

    <table>
        <thead>
            <tr>
                <th>Date in DateTime data type</th>
<th>Date in String data type</th>
<th>Date in LocalDateTime data type</th>
                <th>Other Column</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="item : ${list}">
                <td th:text="${#dates.format(item.date_in_DateTime, 'dd-MM-yyyy HH:mm a')}"></td>
                <td class="date-formatter" th:attr="data-date=${item.date_in_String}"></td>
                <td th:text="${#temporals.format(item.date_in_LocalDateTime, 'dd-MM-yyyy')}"></td>
                <td th:text="${item.otherField}"></td>
            </tr>
        </tbody>
    </table>

    <script th:src="@{/assets/js/date-script.js}"></script>

</body>
</html>

Note: If the date is in string in entity class then need to format the date using JavaScript in thymeleaf.

Date Formatter JavaScript (/assets/js/date-script.js)
// Function to format date string
function formatDateString(dateString) {
const date = new Date(dateString);
const day = String(date.getDate()).padStart(2, '0');
const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-based
const year = date.getFullYear();
return `${day}-${month}-${year}`;
}

// On document load, format all dates
document.addEventListener('DOMContentLoaded', function() {
const dateElements = document.querySelectorAll('.date-formatter');
dateElements.forEach(element => {
const dateString = element.getAttribute('data-date');
element.textContent = formatDateString(dateString);
});
});

No comments:

Post a Comment

Bottom Ad [Post Page]

rrkksinha.