如何更改 Tomcat 7 的服务器时区?

How to change Tomcat 7#39;s server timezone?(如何更改 Tomcat 7 的服务器时区?)

本文介绍了如何更改 Tomcat 7 的服务器时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序部署在美国洛杉矶的 Debian vps 中.所以像 new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()) 这样的代码将返回美国/洛杉矶的当前时间.

My application deployed in a Debian vps in US, Los Angeles. So code like new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()) will return current time of America/Los Angeles.

我可以在 Tomcat 的配置文件(server.xmlcatalina.sh 还是什么?)中进行一些设置,以便获取当前时间将返回指定的 TimeZone,如 GMT+8亚洲/台北 ???

Can I do some setting in Tomcat's configuration file (server.xml or catalina.sh or what?) so that get current time will return a specified TimeZone like GMT+8 or Asia/Taipei ???

推荐答案

对于所有可以设置时区的不同位置,在处理时间时(通常)总是最好明确设置时区.是的,您的服务器在洛杉矶,但您的用户在哪里?

With all of the different places where you can set timezones, it's (in general) always best to explicitly set the timezone when you're dealing with times. Yes, your server is in Los Angeles, but where are your users?

由于显式处理时区会使您的应用程序更复杂(但也更正确、更少令人惊讶、更难测试),因此下一个最好的方法是显式让 tomcat (java) 知道您的服务器时钟设置为哪个时区.小心:有一些级别可以设置:将您的服务器时钟设置为 UTC,将您的服务器操作系统配置为 PST,然后让 java 知道您的服务器所在的时区,例如在 setenv.sh 中执行 CATALINA_OPTS="$CATALINA_OPTS -Duser.timezone=America/Los_Angeles" (或任何您的时区)为您的时区配置 Java.

As explicitly dealing with timezones makes your application somewhat more complex (but also more correct, less surprising, harder to test) the next best would be to explicitly make tomcat (java) know what timezone your server clock is set to. Careful: There are some levels to set this: Set your server clock to UTC, configure your server OS to be PST and then let java know of the timezone that your server is on, e.g. in setenv.sh do CATALINA_OPTS="$CATALINA_OPTS -Duser.timezone=America/Los_Angeles" (or whatever your timezone is) to configure Java for your timezone.

测试、冲洗、重复,直到对配置满意为止.但是,让它成为您可以着手的所有不同级别的明确选择.解析时区是 java 而不是 tomcat 的功能.

Test, rinse, repeat until happy with the configuration. But make it an explicit choice on all different levels that you can set your hands on. Resolving the timezone is rather a java than a tomcat feature.

始终以 UTC 存储时间对于软件的可维护性非常重要.如果你曾经存储在你当地的时区,计算任何其他时区将是一团糟——想想夏令时、世界不同地区的时区变化等等.

It's quite important for maintainability of your software to always store times in UTC. If you ever store in your local timezone, calculating any other timezone will be a mess - think daylight savings times, change of timezones of different areas of the world etc.

所以:将您的服务器设置为 UTC,然后获取当前时间,检查它是否正确.出于显示目的,您可以使用(用户的)本地时区(例如 PST),但对于存储和计算,强烈建议使用 UTC.

So: Set your server to UTC, then get the current time, check if it's correct. For display purposes, you might use the (user's) local timezone (e.g. PST), but for storage and calculation, UTC is highly recommended.

这篇关于如何更改 Tomcat 7 的服务器时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何更改 Tomcat 7 的服务器时区?

基础教程推荐