Freemarker print dates in different time zones

I am using Freemarker version 2.3.20.

I have a data structure that contains two dates, one in local time and one in utc.

// 2017-07-17 18:30 UTC
ZonedDateTime utcTime = ZonedDateTime.of(2017, 7, 17, 18, 30, 0, 0, ZoneId.of("UTC"));
// 2017-07-17 20:30 (+02:00)
ZonedDateTime localTime = utcTime.withZoneSameInstant(ZoneId.of("Europe/Berlin"));

      

Freemarker can only handle java.util.Date

, so I am passing in dates.

Map<String, Object> mapping = new HashMap<String, Object>();
mapping.put("departureTimeLocal", Date.from(localTime.toInstant()));
mapping.put("departureTimeUtc", Date.from(utcTime.toInstant()));

      

In my template, I would like to write something like:

Departure (local): ${departureTimeLocal?string['HH:mm']}
Departure (UTC)  : ${departureTimeUtc?string['HH:mm']}

      

And as a result, I would like to see:

Departure (local): 20:30
Departure (UTC)  : 18:30

      

I am currently seeing:

Departure (local): 20:30
Departure (UTC)  : 20:30    <#-- timestamp interpreted in local time -->

      

I have also tried something like:

Departure (converted): ${(departureTimeLocal?string['yyyy-MM-dd HH:mm'] + ' UTC')?datetime['yyyy-MM-dd HH:mm z']?string['HH:mm']}
--> Departure (converted): 22:30

      

What would be the best way to archive something like this?

Yes, I know: java.util.Date

it doesn't actually have a timezone (print only) and localTime/utcTime.toInstant()

both maps refer to the same moments at zulu time.

+3


source to share


1 answer


With freemarker 2.3.20 you can use iso inline date:

${departureTimeUtc?time?iso_utc_m_nz}

      

This built-in module has been deprecated as of freemarker 2.3.21 and replaced with:

${departureTimeUtc?time?string.iso_m_nz_u}

      



Meaning iso_m_nz_u

:

  • iso

    : use ISO 8601: 2004 format
  • m

    : accurate to the minute
  • nz

    : no time zone
  • u

    : use UTC instead of the default timezone.

A complete list of options can be found here .

+3


source







All Articles