Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring + Thymeleaf: time in user's timezone

How can I print date and time is specified timezone with Thymeleaf? Something like:

<span th:text="${#dates.format(myDate, 'yyyy-MM-dd HH:mm', 'PST')}">2010-01-01 16:30</span>
like image 697
igo Avatar asked Mar 30 '14 11:03

igo


People also ask

How do I get client timezone in Spring Boot?

If you really want to do it yourself use the RequestContextUtils. getTimeZone(request) method. @RequestMapping public String foo(HttpServletRequest request) { TimeZone timezone = RequestContextUtils. getTimeZone(request); ... }

How does Java handle different time zones?

If you cannot change the OS or the JVM timezone, you can still convert a Java Date/Time or Timestamp to a specific time zone using the following two JDBC methods: PreparedStatement#setTimestamp(int parameterIndex, Timestamp x, Calendar cal) – to convert the timestamp that goes to the database.

What is #fields in Thymeleaf?

Class FieldsExpression Object for performing form-field-related operations inside Thymeleaf Standard Expressions in Spring environments. Note a class with this name existed since 1.0, but it was completely reimplemented in Thymeleaf 3.0.


1 Answers

Another approach to the same problem may be to use your own static methods:

${T(xx.xxx.utils.DateUtils).format(myDate, 'yyyy-MM-dd HH:mm', 'CET')}

  public static String format(Date date, String pattern, String timeZone) {
    TimeZone tz = TimeZone.getTimeZone(timeZone);
    return DateFormatUtils.format(date, pattern, tz);
  }

or even directly from lang3 (does not work on GAE because of some class access restrictions in sun.util.calendar package):

<div th:with="timeZone=${T(java.util.TimeZone).getTimeZone('CET')}">
   <span th:text="${T(org.apache.commons.lang3.time.DateFormatUtils).format(myDate, 'yyyy-MM-dd HH:mm', timeZone)}"></span>
</div>
like image 135
Marek Raki Avatar answered Sep 28 '22 16:09

Marek Raki