忽略 thymeleaf 上的语言环境 #date.format()

Ignore locale on thymeleaf #date.format()

我想保留日期格式以固定标准,而不考虑区域设置。但是,默认情况下它采用当前语言环境并根据语言环境设置格式。

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

我一直希望格式像

09-Sep-2015

但是使用 CA 语言环境我得到 09-de set.-2015

有没有办法解决这个问题。

更新 此问题与 不重复。我的问题与区域设置格式有关。

不确定您使用的是 Maven 还是 Gradle。添加 thymeleaf-extras-java8time 作为你的依赖。

而不是 #dates 使用 #temporal 并指定 locale 作为参数,如下所示。

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

但请确保您的 myDatejava.time.* 格式

#temporals.format 函数是正确的使用方法。但是,第三个“语言环境”参数必须是 java.util.Locale 对象,而不是字符串。

以下作品:

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

请注意,即使您使用的是 Kotlin Spring Boot. Thymeleaf 模板中的语法不是 Java,它是一个 OGNL 表达式。

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

我将引用此处使用的有用语法:

#variable
Context variable reference

@class@method(args)
Static method reference

@class@field
Static field reference

new class(args)
Constructor call

编辑:另一个选项是在 Thymeleaf 上下文中指定区域设置,如果您只想覆盖默认系统区域设置。我已经包含了一个 Kotlin 片段,说明它是如何工作的:

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

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