JSTL LocalDateTime 格式

JSTL LocalDateTime format

我想在 "dd.MM.yyyy" 模式中格式化我的 Java 8 LocalDateTime 对象。有没有可以格式化的库?我尝试了下面的代码但出现了转换异常。

<fmt:parseDate value="${date}" pattern="yyyy-MM-dd" var="parsedDate" type="date" />

JSTL 中有LocalDateTime class 的标签或转换器吗?

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));
     }
}

然后创建一个 /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>

最终使用如下:

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

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

如有必要,扩展方法以获取 Locale 参数。

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

使用该库,您的示例将如下所示:

<javatime:parseLocalDateTime value="${date}" pattern="yyyy-MM-dd" var="parsedDate" />

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

不,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 }" />

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

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

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

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

${localDateTimeFormat.parse(date)}

现在可以用JSTL解析了

我建议使用 java.time.format.DateTimeFormatter。 首先将其导入JSP <%@ page import="java.time.format.DateTimeFormatter" %>,然后格式化变量${localDateTime.format( DateTimeFormatter.ofPattern("dd.MM.yyyy"))}。 作为 java 开发的新手,我很感兴趣这种方法在 'best practice' 方面是否可以接受。