Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF convertDateTime renders the previous day

Tags:

java

date

jsf

jsf-2

A date (as the Date temporal type) is stored in my DB like this: 31.10.2012
When I display it in the UI, it is rendered like this per default: 2012-10-31
I convert it using <f:convertDateTime pattern="dd.MM.yyyy" /> and unexpectedly it turns to
30.10.2012

The SimpleDateconverter, fed with the same date and the same format string returns 31.10.2012, as expected.

What am I missing?

Thank you

EDIT : for dates stored as Timestamp the same conversion yields correct results, so I suppose it has something to do with the Date interpreted as the exact midnight which in turn might be interpreted to belong to 2 different days. But I still have no clue where to define the behaviour and what would be the best workaround.

like image 678
kostja Avatar asked Sep 10 '12 11:09

kostja


1 Answers

This is undoubtedly a timezone-related issue.

JSF defaults to GMT (UTC) in date/time conversion. So if your server platform default timezone is GMT+X (not GMT-X), then the time will go back in the past X-amount of hours. If the time is already 00:00:00 (midnight), then the date will even go back one day in the past.

There are 2 standard ways to achieve your functional requirement anyway:

  1. Tell JSF to use the server platform default timezone instead for all date/time conversion by adding the following context parameter to web.xml:

    <context-param>
        <param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
        <param-value>true</param-value>
    </context-param>
    
  2. Alter every <f:convertDateTime> to explicitly specify the webapp-specific timezone. As you're based in Germany and the date format pattern also confirms this, I'll assume CET.

    <f:convertDateTime ... timeZone="CET" />
    

In any case, using a non-universal or even mixed timezone throughout the application is not recommendable. It's recommend to set the timezone in all layers and environments to UTC. Not only in the server and front end tier and presentation layer, but also in the SQL database and back end tier and persistence layer. This way the code is not sensitive to timezone and DST(!) related matters and you can just focus on altering the timezone during presentation only, if necessary.

See also:

  • Daylight saving time and time zone best practices
like image 101
BalusC Avatar answered Oct 23 '22 14:10

BalusC