在 Thymeleaf 中格式化 th:field

在 Thymeleaf 中格式化 th:field

问题描述:

我在 Thymeleaf 中有一个表单输入字段.字段(下面代码片段中的 bookingEntry.datefrom)是日期类型.我使用日期选择器来允许用户选择和格式化输入字段所需的日期.这一切都很好.

I have a form input field in Thymeleaf. The field (bookingEntry.datefrom in the code snippet below) is type Date. I use a datepicker to allow the user to select and format the required date to enter the field. This is all fine.

但是,我希望以我选择的格式显示日期的初始值(我已设置为当前日期).那么,我如何格式化最初显示在 th:field 中的日期.th:value 被忽略(Thymeleaf 正在从支持对象中获取值,因为它应该)而且我似乎无法将格式应用于 th:field.

However, I want the initial value of the date (which I have set to the current date) to be displayed in the format that I choose. So, how do I format the date initially shown in a th:field. th:value is ignored (Thymeleaf is getting the value from the backing object, as it should) and I can't seem to apply a format to the th:field.

Thymeleaf 代码是:

Thymeleaf code is:

<input type="text" class="form-control getdate"
       th:field="*{datefrom}" placeholder="Date From"
       th:value="${#dates.format(bookingEntry.datefrom, 'dd-MMM-yyyy')}"/>

我确信我可以使用以我选择的任何格式初始化的字符串,而不是日期类型,但我想知道是否有办法在 th:field 中格式化初始值?

I'm sure that I could use a String which is initialise in any format that I choose, rather than a Date type, but I wondered if there was a way to format initial values in a th:field?

非常感谢

我错过了简单的答案,仅仅是因为我对 Spring 的了解有限.我在这里添加它以防它可以帮助像我这样的任何其他新手.传递给表单的对象中元素上的 @DateTimeFormat 注释完成了这项工作.它确保 Date 对象以您希望的方式格式化(无论您是否使用 Thymeleaf).

I missed the simple answer, simply because of my limited knowledge of Spring. I'm adding it here incase it helps any other novices like me. The @DateTimeFormat annotation on the element in the object being passed to the form does the job. It ensures that the Date object is formatted in the way that you wish (irrespective of whether you are using Thymeleaf or not).

在上面的例子中,在 bookingEntry 对象中

In the example above, within the bookingEntry object

@Temporal(DATE)
@DateTimeFormat (pattern="dd-MMM-YYYY")
private Date datefrom;