Thymeleaf timezone

Viewed 57

I want to get current time in GMT+6 but can not make it work. what is the correct format to pass the timezone?

I've tried the followings -

[[${#dates.createNowForTimeZone('ASIA/DHAKA')}]]

[[${#dates.createNowForTimeZone("ASIA/DHAKA")}]]

[[${#dates.createNowForTimeZone('GMT+6')}]]
[[${#dates.createNowForTimeZone("GMT+6")}]]

But, all give the time in EDT.

1 Answers

I recommend you use the Thymeleaf "extras" library for handling Java 8's java.time classes, and avoid anything related to the old and flawed java.util.Date class.

The library:

Thymeleaf - Module for Java 8 Time API compatibility

If you are using Maven, you can add it to your project using the following dependency:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

Otherwise you can download the JARs manually from here.


Once you have installed the new JAR, you can use this:

${#temporals.createNowForTimeZone(zoneId)}     // return a instance of java.time.ZonedDateTime

For example, as follows:

<div th:text="${#temporals.createNowForTimeZone('Asia/Dhaka')}"></div>

Or, using the syntax in your question, as follows:

[[${#temporals.createNowForTimeZone('Asia/Dhaka')}]]

Example output:

2022-05-19T18:57:32.190245400+06:00[Asia/Dhaka]

That was generated for the target timezone, when my local datetime was Thu May 19 08:57:32 EDT 2022.


Note about zone IDs:

You can read about valid zone IDs here. In your case, you need to be careful to match the exact case of the ID text - so it has to be Asia/Dhaka - not ASIA/DHAKA.

See also Where is the official list of zone names for java.time?


Note about formatting

There is a chance that you are going to want to format the date string, in which case take a look at the various #temporals.format() functions listed here.

But you may also want to consider formatting the string in Java, to keep your Thymeleaf template less cluttered.

Related