Teddy Teddy - 1 year ago 370
Java Question

Make long value as date and format it in Thymeleaf

I have this line in my Thymeleaf template.

<td th:text="${activity.loggedTimestamp}"></td>

I want to convert this long value into a date before formatting it. If it was already a date I would have done this:

<td th:text="${#dates.format(activity.loggedTimestamp)}"></td>

But, since its a long value, I want to make it a date first.

I found some related methods in the documentation. But, not matching with my requirements.

* Create date (java.util.Date) objects from its components

* Create a date (java.util.Date) object for the current date and time

* Create a date (java.util.Date) object for the current date (time set to 00:00)

Answer Source

Quoting ThymeLeaf documentation:

We already mentioned that ${...} expressions are in fact OGNL (Object-Graph Navigation Language) expressions executed on the map of variables contained in the context.

For detailed info about OGNL syntax and features, you should read the OGNL Language Guide at: http://commons.apache.org/ognl/

So you follow that link to the OGNL documentation:

You can create new objects as in Java, with the new operator. One difference is that you must specify the fully qualified class name for classes other than those in the java.lang package.

This is only true with the default ClassResolver in place. With a custom class resolver packages can be mapped in such a way that more Java-like references to classes can be made. Refer to the OGNL Developer's Guide for details on using ClassResolver class (for example, new java.util.ArrayList(), rather than simply new ArrayList()).

OGNL chooses the right constructor to call using the same procedure it uses for overloaded method calls.


You write:

<td th:text="${#dates.format(new java.util.Date(activity.loggedTimestamp))}"></td>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download