在 Thymeleaf 日期输入中设置 th:value?

sma*_*ter 1 html datepicker default-value thymeleaf

我使用 Thymeleaf,我想在用户编辑之前向用户显示现有的日期值,而且如果他们不想编辑它,也可以保持原样。我一直在尝试设置日期输入值,但它不起作用。

我尝试过的:

艺术家:

private Date dateDebut;
Run Code Online (Sandbox Code Playgroud)

控制器:

String dateDebut = Artist.getDateDebut().toString();
model.addAttribute("dateDebut", dateDebut);
Run Code Online (Sandbox Code Playgroud)

看法:

<input type="date" class="form-control" name="dateDebut" th:value="${dateDebut}" />
Run Code Online (Sandbox Code Playgroud)

然而这不起作用。它仍然向我显示这样的日期输入: https: //i.stack.imgur.com/MdZIw.png,而不是我试图显示的设置值。

我尝试过使用 Bootstrap datepicker 但它也不起作用。请问有什么建议吗?

Met*_*ids 7

  1. 如果您使用type="date",则浏览器可以选择日期的格式。如果你想自己格式化,你必须使用type="text".

  2. th:value="${dateDebut}"不会尊重你的@DateTimeFormat注释。如果您希望 thymeleaf 以该格式输出,您应该使用双括号语法(th:value="${{dateDebut}}"例如)或使用th:field替代(这将意味着其他更改)。在这种情况下,前者可能更好。

编辑:

如果您想使用type="date",请保留注释@DateTimeFormat (pattern="yyyy-MM-dd")并使用双括号:

<input type="date" class="form-control" name="dateDebut" th:value="${{dateDebut}}" />
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用日期格式化函数:

<input type="date" class="form-control" name="dateDebut" th:value="${#dates.format(dateDebut, 'yyyy-MM-dd')}" />
Run Code Online (Sandbox Code Playgroud)