Get current date in Thymeleaf

This one works fine for me:

${#dates.format(#dates.createNow(),'YYYY/MM/dd HH:mm')}


Try with this:

${#dates.format(#dates.createNow(), 'dd MMM yyyy HH:mm')}

will be created a java.util.Date() object then formatted as you prefer.


Using the #calendars utility object

This is an alternative method:

${#calendars.format(#calendars.createNow(), 'dd MMM yyyy HH:mm')}

the result will be the same.


The Date is going to be processed by the #dates utility.
The new LocalDateTime, LocalDate classes are going to be processed by the #temporals utility.

Set the format:

<p th:text="${#dates.format(standardDate, 'dd-MM-yyyy HH:mm')}"></p>
<p th:text="${#temporals.format(localDateTime, 'dd-MM-yyyy HH:mm')}"></p>
<p th:text="${#temporals.format(localDate, 'MM-yyyy')}"></p>

Where you have to sent it to a view as following:

model.addAttribute("standardDate", new Date());
model.addAttribute("localDateTime", LocalDateTime.now());
model.addAttribute("localDate", LocalDate.now());

Formatting the LocalDate is only possible if we will specify only the particular date fields, skipping the time fields.

Output result:

24-05-2019 21:57
24-05-2019 21:57
24-05-2019

Just another way to get the current date and time in thymeleaf is using,

${execInfo.now}

The current date and time (${execInfo.now}), a Calendar object corresponding to the moment the template engine started its execution for this template.

You can create an WebContext to modify the context variables,

WebContext ctx = new WebContext(request, servletContext, request.getLocale());

When the context is created, it creates a object which holds the two values for the template engine. The object name is execInfo. The two variables are templateName and now. These variables can be accessed across anywhere in the templates.

If you need to format the date format you can do like this,

WebContext ctx = new WebContext(request, servletContext, request.getLocale());
ctx.setVariable("today", dateFormat.format(cal.getTime()));

Example:

Current time : <div th:text="${execInfo.now.time}">Wed Feb 10 13:55:58 IST 2016</div>