Erfan Ahmed
Erfan Ahmed

Reputation: 1613

Thymeleaf timezone

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.

Upvotes: 2

Views: 716

Answers (1)

andrewJames
andrewJames

Reputation: 22032

UPDATE November 2022

Thymeleaf version 3.1 now includes built-in support for java.time:

The thymeleaf-extras-java8time extras module has been integrated into the Thymeleaf core: the #temporals expression utility object is now always available.

You no longer need to add the extra JAR mentioned below, for Thyeleaf 3.1 onwards.

(Spring Boot 3.0 uses Thymeleaf 3.1, if you are using that.)


Thymeleaf 3.0 and earlier

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.

Upvotes: 4

Related Questions