Oct 5, 20" /> Oct 5, 20" /> Oct 5, 20"/>
DEVHIDE
  • Home (current)
  • About
  • Contact
  • Cookie
  • Home (current)
  • About
  • Contact
  • Cookie
  • Disclaimer
  • Privacy
  • TOS
Login Or Sign up

How to format Dates in Thymeleaf

47 Views Asked by Nuñito Calzada At 30 March 2024 at 16:18 2025-12-07T14:26:48.692000

I've tried this:

<p class="post-date">
                    <time datetime="2023-01-01" th:text="${#temporals.format(item.getCreatedDate(), 'dd-MM-yyyy HH:mm')}">Oct 5, 2023</time>
                  </p>

where createdDate is a java.util.Date

but I am getting this error:

2024-03-30 17:15:58.620 ERROR [] o.a.c.c.C.[.[.[.[dispatcherServlet]@log(175) - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#temporals.format(item.getCreatedDate(), 'dd-MM-yyyy HH:mm')" (template: "blog-details" - line 109, col 49)] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method format(java.sql.Timestamp,java.lang.String) cannot be found on type org.thymeleaf.expression.Temporals
    at org.springframework.expression.spel.ast.MethodReference.findAccessorForMethod(MethodReference.java:237)
    at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:147)
    at org.springframework.expression.spel.ast.MethodReference$MethodValueRef.getValue(MethodReference.java:400)
java spring spring-boot thymeleaf spring-thymeleaf
Original Q&A
2

There are 2 best solutions below

2
phuc16102001 phuc16102001 On 30 March 2024 at 18:01 BEST ANSWER

How about trying this one?

<p class="post-date">
  <time datetime="2023-01-01" th:text="${#dates.format(item.getCreatedDate(), 'dd-MM-yyyy HH:mm')}">Oct 5, 2023</time>
</p>

Explaination:

I saw that the error said the method format of org.thymeleaf.expression.Temporals does not have the prototype of (java.sql.Timestamp, java.lang.String). So I can understand that your item.getCreatedDate() is java.sql.Timestamp class:

package java.sql;

public class Timestamp extends java.util.Date {
   ...
}

This class is extends of java.util.Date, so you can use org.thymeleaf.expression.Dates instead:

package org.thymeleaf.expression;

public final class Dates {
    public String format(final Date target, final String pattern) {
       ...
    }
}
0
rzwitserloot rzwitserloot On 30 March 2024 at 17:29

Your method item.getCreatedDate() returns an Instant.

This means a few things:

  • That's a horrible name. You really should rename that method. That, or, make it return a LocalDate instead, then the name is fine. dates aren't timestamps. Confusion in what kind of temporal concept is being returned is pernicious: Many places allow implicit conversion between types that cannot actually be implicitly converted, resulting in bugs. The kinds of bugs you don't find with tests because they only occur during timezone or daylight saving time mismatches.
  • temporals can't format Instant because you're not supposed to: Instants are a moment in time, as the universe measures it: It is not meant to represent, interact, or be suitable for any operation that is based on human reckoning of time (days/months/years/hours/timezones: That's human reckoning. 'millis since epoch', that's computer reckoning). For example, Instants do not encode a timezone at all. They just encode a moment in time. Hence, it is not possible to render it in human terms! To do that, you must first have a timezone; "What month is that instant in time in?" cannot be answered. Only questions like: "What month is that instant in time in... in Amsterdam?" - that can be answered. You must specify a timezone for it to do its job - which you do by converting your Instant to e.g. a ZonedDateTime. That does contain all required info to render it in human reckoning terms, and, indeed, temporals's format can deal with ZDTs (or LocalDateTime instances, your choice) just fine.

Either fix your getCreatedDate() method to return something more appropriate for the job, or, convert the Instant that it returns into a ZDT using:

.getCreatedInstant().atZone(ZoneId.of("Europe/Amsterdam"));

// or
.getCreatedInstant().atZone(ZoneOffset.UTC);

Related Questions in JAVA

  • I need the BIRT.war that is compatible with Java 17 and Tomcat 10
  • Creating global Class holder
  • No method found for class java.lang.String in Kafka
  • Issue edit a jtable with a pictures
  • getting error when trying to launch kotlin jar file that use supabase "java.lang.NoClassDefFoundError"
  • Does the && (logical AND) operator have a higher precedence than || (logical OR) operator in Java?
  • Mixed color rendering in a JTable
  • HTTPS configuration in Spring Boot, server returning timeout
  • How to use Layout to create textfields which dont increase in size?
  • Function for making the code wait in javafx
  • How to create beans of the same class for multiple template parameters in Spring
  • How could you print a specific String from an array with the values of an array from a double array on the same line, using iteration to print all?
  • org.telegram.telegrambots.meta.exceptions.TelegramApiException: Bot token and username can't be empty
  • Accessing Secret Variables in Classic Pipelines through Java app in Azure DevOps
  • Postgres && statement Error in Mybatis Mapper?

Related Questions in SPRING

  • HTTPS configuration in Spring Boot, server returning timeout
  • Multi Tenancy in Spring - Partitioned Data Approach
  • How to create beans of the same class for multiple template parameters in Spring
  • org.telegram.telegrambots.meta.exceptions.TelegramApiException: Bot token and username can't be empty
  • Springboot: How to get an entity optional property and check null?
  • How do I propagate the current SecurityContext to my @RabbitListener in Spring Boot?
  • Spring's XML based bean configuration for Object Mapper's Case Insensitive property
  • Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. I'm using Postgresql
  • springboot class org.hibernate.mapping.Bag cannot be cast to class org.hibernate.mapping.SimpleValue
  • Issue while deploying JDK 17 and Spring 6 application in Tomcat 10.1.20
  • Spring JPA Data Auditing - How to design it?
  • Springframework test: Async not started
  • Error: Cannot invoke "jakarta.servlet.http.HttpSession.getAttribute(String)" because "session" is null
  • How does spring-retry determine which methods to retry when @Retryable is placed at the class level?
  • problem with edge server registration in Eureka

Related Questions in SPRING-BOOT

  • Multi Tenancy in Spring - Partitioned Data Approach
  • I have created a spring boot application with spring data JPA, Rest ,oracle and i am getting this ORA-00933: SQL command not properly ended
  • Springboot: How to get an entity optional property and check null?
  • How to create jasper report in spring boot rest api with jpa
  • JSON Body is Not Passing Certain Strings
  • Unresolved reference error is showing up after adding the dgs codegen plugin successfully
  • Transaction silently rolled back
  • JPA buddy error when generating JPA Entities from DB
  • Migrating Spring Boot 2 to 3 throws org.glassfish.jaxb.runtime.v2.runtime.IllegalAnnotationsException: 3 counts of IllegalAnnotationExceptions
  • Hibernate SQL Error: Missing FROM-clause entry for table "th1_1"
  • Appwrite and / or Spring Boot Backend
  • Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. I'm using Postgresql
  • Driver com.microsoft.sqlserver.jdbc.SQLServerDriver claims to not accept jdbcUrl, ${SPRING_DATASOURCE_URL}: GitHub Actions
  • springboot class org.hibernate.mapping.Bag cannot be cast to class org.hibernate.mapping.SimpleValue
  • Spring security causing 404 with message "No static resource login"

Related Questions in THYMELEAF

  • How to format Dates in Thymeleaf
  • CSS applied for one endpoint but not for another in Thymeleaf
  • th:style isn't working in my project depending on case true:false
  • Thymeleaf does not use UTF-8 to transmit form data to rest endpoint
  • Unresloved dependency in maven
  • Can you help a tag look at the static resource path without looking at the controller
  • style tag with Thymeleaf
  • Can JSTL or Custom Tag Libraries be Called from Thymeleaf?
  • I can't get redirected to my update page in Spring Boot 3 using Thymeleaf
  • thymeleaf utext unescaped html not interpreted by browser
  • How to register a formatter for a type in ThymeLeaf (non-web environment)
  • Dynamically adding "active" class to a link based on the current url in thymeleaf and spring boot 3
  • How object passes from controller to html page in Thymeleaf
  • How do I specify user properties with Thymeleaf?
  • Creating and filling the parts and subparts of a file

Related Questions in SPRING-THYMELEAF

  • Thymeleaf generated text in TEXT mode replaces CRLF with LF?
  • How to secure endpoints and pages with Spring Security oAuth2 (Using auth0)
  • :before :after pseudo elements CSS not getting rendered in my PDF
  • Thymeleaf expression to get list from yaml using text template mode
  • Uncaught TypeError: row.querySelector(...) is null | Spring Boot, Thymeleaf, Bootstrap, Script
  • @PutMapping doesn't work in my SpringBoot project
  • Unable to install Thymeleaf plugin to the Spring Tool Suite-4-4.20.1
  • Thymeleaf not redirecting to any page beside index.html
  • How to save a table without auto save other table when used @ManyToOne and @JoinColumn
  • Nested block not allowed
  • error: Refused to apply style from ... because its MIME type ('text/html') is not a supported stylesheet MIME type
  • How does BindingResult.rejectValue(...) work with Object[] errorArgs?
  • SpringTemplateEngine process with parallelStream
  • spring boot/thymeleaf foreach, error on handling controller
  • How can I set authority variables using Java Spring Security Expressions in Thymeleaf?

Trending Questions

  • UIImageView Frame Doesn't Reflect Constraints
  • Is it possible to use adb commands to click on a view by finding its ID?
  • How to create a new web character symbol recognizable by html/javascript?
  • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
  • Heap Gives Page Fault
  • Connect ffmpeg to Visual Studio 2008
  • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
  • How to avoid default initialization of objects in std::vector?
  • second argument of the command line arguments in a format other than char** argv or char* argv[]
  • How to improve efficiency of algorithm which generates next lexicographic permutation?
  • Navigating to the another actvity app getting crash in android
  • How to read the particular message format in android and store in sqlite database?
  • Resetting inventory status after order is cancelled
  • Efficiently compute powers of X in SSE/AVX
  • Insert into an external database using ajax and php : POST 500 (Internal Server Error)

Popular # Hahtags

javascript python java c# php android html jquery c++ css ios sql mysql r reactjs

Popular Questions

  • How do I undo the most recent local commits in Git?
  • How can I remove a specific item from an array in JavaScript?
  • How do I delete a Git branch locally and remotely?
  • Find all files containing a specific text (string) on Linux?
  • How do I revert a Git repository to a previous commit?
  • How do I create an HTML button that acts like a link?
  • How do I check out a remote Git branch?
  • How do I force "git pull" to overwrite local files?
  • How do I list all files of a directory?
  • How to check whether a string contains a substring in JavaScript?
  • How do I redirect to another webpage?
  • How can I iterate over rows in a Pandas DataFrame?
  • How do I convert a String to an int in Java?
  • Does Python have a string 'contains' substring method?
  • How do I check if a string contains a specific word?
.

Copyright © 2021 Jogjafile Inc.

  • Disclaimer
  • Privacy
  • TOS
  • Homegardensmart
  • Math
  • Aftereffectstemplates