Get the current date in Timeleaf

How can I print the current date (and time, after all) from Thymeleaf? I try these functions: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#dates but I cannot get them to work.

+10
java spring date thymeleaf
source share
5 answers

Try the following:

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

a java.util.Date() object will be created, which will be 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.

+25
source share

This works fine for me:

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

+5
source share

Another way is used to get the current date and time in thimeleaf,

 ${execInfo.now} 

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

You can create a WebContext to change context variables,

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

When a context is created, it creates an object that contains two values ​​for the template engine. The name of the execInfo object. Two variables: templateName and now . These variables can be accessed anywhere in the templates.

If you need to format the date format, you can do it 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> 
+1
source share

Date will be processed by the #dates utility.
New LocalDateTime , LocalDate will 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 should send it to view as follows:

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

LocalDate formatting is LocalDate possible if we specify only certain date fields, skipping time fields.

Output Result :

 24-05-2019 21:57 24-05-2019 21:57 24-05-2019 
+1
source share

I hope this works:

 <b th:text="${#execInfo.now.time}"></b> 
0
source share

All Articles