Java – JSTL and time zone
I have some questions about the time zone We store all dates in UTC time, but we need to display some of them both in local (eastern US) time and UTC
This is my test. I have a UTC date and want to display it in UTC and local time:
<html> <!-- let's assume this date is in UTC,I get it from Database in my code --> <jsp:useBean id="dateValue" class="java.util.Date" /> GMT <fmt:formatDate value="${dateValue}" pattern="yyyy-MM-dd HH:mm:ss z" timeZone="GMT"/> </html> <!-- Displays the original time +4 - not what I need--> No time zone <fmt:formatDate value="${dateValue}" pattern="yyyy-MM-dd HH:mm:ss z"/> <!-- Displays the original time,but timezone is EDT --> US/Eastern <fmt:formatDate value="${dateValue}" pattern="yyyy-MM-dd HH:mm:ss z" timeZone="US/Eastern"/> <!-- Displays the original time,timezone is EDT,I need original + 4 --> </html>
Again: I have a UTC time from the database. I want to format it and display it in UTC time zone The server runs in a time zone other than UTC
Basically, I need a function like this
convertToTimezone(date,originalTimeZone,desiredTimeZone).
FMT: what does formatdate provide
convertToTimezone(date,serverTimeZone,desiredTimeZone).
I can crack it, but it usually causes problems when saving daylight time, etc
PS: for those looking for answers - one thing to do is to run the server in UTC, so the conversion is OK If you can't change it, the only way is to create a new date in UTC time zone. Specifically, I convert my text time myself, and then create a new date and provide the text and UTC time zone If not, the time zone is read from the server
Solution
I don't understand your problem business as usual. You seem to expect the new date () to treat the computer time as GMT, which is 19:21 GMT This is wrong It calculates the actual GMT time based on the computer's time zone FMT: settimezone does not change the time zone of the computer, nor does it change the result of the new date() FMT: settimezone only sets the default time zone for all dates formatted by FMT: formatdate This operation is enforced only if the computer's time zone is not GMT
Remove FMT: settimezone and you will see the date (incorrectly) closed for 4 hours Then use - duser Timezone = UTC starts the server (to override the default computer time zone), and you will see again that it is correct You can also try to use the actual date in the DB instead of the new date ()
In any case, it is not a good practice to run servers in time zones other than UTC It will only cause trouble for all colors I strongly recommend running the server in UTC format If you do not want to change the time zone of your computer for some reason, you can change the time zone of your computer by setting - duser Timezone = UTC is implemented by adding VM parameters to the server Always use UTC and apply the time zone only when you display it to end users See also DST and timezone best practices