Thymeleaf Date Picker Example

Thymeleaf Date Picker Example

使用 Thymeleaf 和 Java 8 日期和时间 API 创建日期选择器

本教程将引导你使用 Thymeleaf 和 Java 8 日期和时间 API 创建日期选择器。

1. 引入依赖

首先,你需要引入 thymeleaf-extras-java8time 依赖,它支持 Java 8 中的日期和时间 API。

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

2. 引入命名空间和类型转换器

在你的 HTML 文件中,你需要引入 java8 命名空间和类型转换器,以便使用 Java 8 日期和时间 API。

<html xmlns:th="http://www.thymeleaf.org"
      xmlns:java8="http://www.thymeleaf.org/extras/java8time"
      th:include="fragments/header :: header">
<!-- Date time format -->
<java8:format value="${#dates.format(date, 'yyyy-MM-dd')}" pattern="yyyy-MM-dd" />

3. 创建日期输入框

使用 th:field 指令创建日期输入框,并指定日期格式。

<div class="form-group">
    <label for="date">Date</label>
    <input type="date" th:field="*{date}" th:attr="java8:pattern=${'yyyy-MM-dd'}" class="form-control" required />
</div>

完整代码

<html xmlns:th="http://www.thymeleaf.org"
      xmlns:java8="http://www.thymeleaf.org/extras/java8time"
      th:include="fragments/header :: header">

<head>
    <title>Thymeleaf Date Picker Example</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

<body>
    <div class="container">
        <h1>Thymeleaf Date Picker Example</h1>
        <form method="post" th:action="@{/save}">
            <div class="form-group">
                <label for="date">Date</label>
                <input type="date" th:field="*{date}" th:attr="java8:pattern=${'yyyy-MM-dd'}" class="form-control" required />
            </div>
            <button type="submit" class="btn btn-primary">Save</button>
        </form>
    </div>
</body>

</html>

现在你已经成功地使用 Thymeleaf 和 Java 8 日期和时间 API 创建了一个日期选择器!

Thymeleaf 日期选择器:使用 Java 8 日期和时间 API

原文地址: https://www.cveoy.top/t/topic/nsTK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录