1

I am writing a spring boot application using Thymeleaf as template engine.

The issue is I am getting UTC server time displayed on UI instead of client time (GMT +3):

Actual result: 10-May-2021 19:20:30

Expected result: 10-May-2021 22:20:30

I found a solution using javascript here: Convert UTC date time to local date time

in header:

<script type="text/javascript">
        function localize(t)
        {
            var d=new Date(t+" UTC");
            document.write(d.toString());
            document.write(d.toString().replace(/GMT.*/g,""));
        }
</script>

in body:

<script type="text/javascript">localize("6/29/2011 4:52:48 PM");</script>

and it works..

however, I do not know how to incorporate this code into my Thymeleaf template:

<table class="table table-bordered table-striped ">
        <thead class="thead-dark">
        <tr>
          ...

            <th></th>
        </tr>
        </thead>

        <tbody>
        <tr th:each="tempReport : ${page}">
            
           ...

            <td th:text="${#dates.format(tempReport.createdAt, 'dd-MMMM-yyyy HH:mm:ss')}"></td>

        </tr>
        </tbody>
</table>

Any help to incorporate the javascript code into Thymeleaf template will be appreciated! Any other approaches to convert the time are welcome as well!

 skipper
  • 53
  • 4
  • 1
    Thymeleaf runs on the server. It does not exist in the browser (it replaces itself with the required HTML). Therefore you cannot execute a client-side JavaScript function (`localize(t)`) during a server-side rendering loop (`th:each="tempReport : ${page}"`). One simple alternative: You can process your dates on the server, before passing them to the Thymeleaf renderer. – andrewJames May 11 '21 at 13:12
  • @andrewjames Oh.. did not know about that.. Thank you so much! Need to find backend solutions then –  skipper May 11 '21 at 13:38
  • @andrewjames I came across your comment here: https://stackoverflow.com/questions/66246152/thymeleaf-temporals-and-dates-with-timezone where you suggested some code on server side to show client's timezone on their UI. Do you have any idea how can I implement your code in my spring boot app, where should I put it? Will it work in this way? –  skipper May 11 '21 at 23:52
  • 1
    I do not use Spring Boot very much, so I cannot give a good answer. But I would expect this code to be placed in the controller which maps Java data to the HTML template. I believe the updated data would then be pushed to the template using `model.addAttribute("someName", someData)`. – andrewJames May 12 '21 at 00:33

0 Answers0