want2learn
want2learn

Reputation: 2511

Ignore locale on thymeleaf #date.format()

I want to keep date format to fix standard regardless of locale. But however it is by default taking current locale and setting format based on locale.

th:text="${#dates.format(myDate, 'dd-MMM-yyyy')}"

I am always expecting format be like

09-Sep-2015

but with CA locale I am getting 09-de set.-2015

Is there a way to fix this.

UPDATE This question is not duplicate of This question. My problem is related to locale formatting.

Upvotes: 2

Views: 1041

Answers (2)

cbreezier
cbreezier

Reputation: 1314

The #temporals.format function is the correct one to use. However, the third "locale" argument must be a java.util.Locale object, not a string.

The following work:

  • #temporals.format(myDate, 'dd-MM-yyyy', new java.util.Locale('en'))
  • #temporals.format(myDate, 'dd-MM-yyyy', @java.util.Locale@ENGLISH)

Note that this is true even if you're working with Kotlin Spring Boot. The syntax in the Thymeleaf template isn't Java, it's an OGNL Expression.

https://commons.apache.org/proper/commons-ognl/language-guide.html

I'll quote the useful syntax used here:

#variable
Context variable reference

@class@method(args)
Static method reference

@class@field
Static field reference

new class(args)
Constructor call

Edit: one other option is to specify the Locale in the Thymeleaf context, if you just want to override the default system Locale. I've included a Kotlin snippet of how that might work:

val context = Context() // org.thymeleaf.Context
context.locale = Locale.ENGLISH
context.setVariable("x", 0)

templateEngine.process("classpath:template.html", context)

Upvotes: 0

user9735824
user9735824

Reputation: 1256

Not sure you are using Maven or Gradle. Add thymeleaf-extras-java8time as your dependency.

and instead of #dates use #temporal and specify locale as parameters as below.

th:text="${#temporals.format(myDate, 'dd-MMM-yyyy','en')}"

But make sure your myDate is in java.time.* format

Upvotes: 0

Related Questions