JSTL LocalDateTime格式

Ugu*_*tun 10 jsp jstl date-format java-time

我想以"dd.MM.yyyy "模式格式化我的java 8 LocalDateTime对象.有格式的库吗?我尝试了下面的代码,但得到了转换异常.

<fmt:parseDate value="${date}" pattern="yyyy-MM-dd" var="parsedDate" type="date" />
Run Code Online (Sandbox Code Playgroud)

在JSTL中是否有LocalDateTime类的标记或转换器?

Bal*_*usC 21

它在14岁的JSTL中不存在.

您最好的选择是创建自定义EL功能.首先创建一个实用方法.

package com.example;

public final class Dates {
     private Dates() {}

     public static String formatLocalDateTime(LocalDateTime localDateTime, String pattern) {
         return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
     }
}
Run Code Online (Sandbox Code Playgroud)

然后创建一个/WEB-INF/functions.tld其中您将实用程序方法注册为EL函数:

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1">

    <tlib-version>1.0</tlib-version>
    <short-name>Custom_Functions</short-name>
    <uri>http://example.com/functions</uri>

    <function>
        <name>formatLocalDateTime</name>
        <function-class>com.example.Dates</function-class>
        <function-signature>java.lang.String formatLocalDateTime(java.time.LocalDateTime, java.lang.String)</function-signature>
    </function>
</taglib>
Run Code Online (Sandbox Code Playgroud)

最后使用如下:

<%@taglib uri="http://example.com/functions" prefix="f" %>

<p>Date is: ${f:formatLocalDateTime(date, 'dd.MM.yyyy')}</p>
Run Code Online (Sandbox Code Playgroud)

必要时扩展Locale参数的方法.


sar*_*gue 11

实际上我遇到了同样的问题,并最终分配了原始的Joda Time jsp标签来创建Java 8 java.time JSP标签.

使用该库,您的示例将是这样的:

<javatime:parseLocalDateTime value="${date}" pattern="yyyy-MM-dd" var="parsedDate" />
Run Code Online (Sandbox Code Playgroud)

检查存储库以获取安装说明:https://github.com/sargue/java-time-jsptags


ege*_*men 6

不,LocalDateTime不存在。

但是,您可以使用:

<fmt:parseDate value="${ cleanedDateTime }" pattern="yyyy-MM-dd'T'HH:mm" var="parsedDateTime" type="both" />
<fmt:formatDate pattern="dd.MM.yyyy HH:mm" value="${ parsedDateTime }" />
Run Code Online (Sandbox Code Playgroud)


ale*_*ric 5

这是我的解决方案(我使用的是 Spring MVC)。

在控制器中添加一个带有 LocalDateTime 模式的 SimpleDateFormat 作为模型属性:

model.addAttribute("localDateTimeFormat", new SimpleDateFormat("yyyy-MM-dd'T'hh:mm"));
Run Code Online (Sandbox Code Playgroud)

然后在JSP中使用它来解析LocalDateTime并得到一个java.util.Date:

${localDateTimeFormat.parse(date)}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用 JSTL 解析它。