强制 Java 时区为 GMT/UTC

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2627992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:04:46  来源:igfitidea点击:

Force Java timezone as GMT/UTC

javatimezoneutcgmt

提问by SyBer

I need to force any time related operations to GMT/UTC, regardless the timezone set on the machine. Any convenient way to so in code?

无论机器上设置的时区如何,我都需要将任何与时间相关的操作强制为 GMT/UTC。在代码中这样做有什么方便的方法吗?

To clarify, I'm using the DB server time for all operations, but it comes out formatted according to local timezone.

澄清一下,我在所有操作中都使用数据库服务器时间,但它根据本地时区进行格式化。

Thanks!

谢谢!

采纳答案by Kevin Brock

The OP answered this question to change the default timezone for a single instance of a running JVM, set the user.timezonesystem property:

OP 回答了这个问题以更改正在运行的 JVM 的单个实例的默认时区,设置user.timezone系统属性:

java -Duser.timezone=GMT ... <main-class>

If you need to set specific time zones when retrieving Date/Time/Timestamp objects from a database ResultSet, use the second form of the getXXXmethods that takes a Calendarobject:

如果在从数据库中检索日期/时间/时间戳对象时需要设置特定的时区ResultSet,请使用getXXX采用Calendar对象的方法的第二种形式:

Calendar tzCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
ResultSet rs = ...;
while (rs.next()) {
    Date dateValue = rs.getDate("DateColumn", tzCal);
    // Other fields and calculations
}

Or, setting the date in a PreparedStatement:

或者,在 PreparedStatement 中设置日期:

Calendar tzCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
PreparedStatement ps = conn.createPreparedStatement("update ...");
ps.setDate("DateColumn", dateValue, tzCal);
// Other assignments
ps.executeUpdate();

These will ensure that the value stored in the database is consistent when the database column does not keep timezone information.

当数据库列不保留时区信息时,这些将确保存储在数据库中的值是一致的。

The java.util.Dateand java.sql.Dateclasses store the actual time (milliseconds) in UTC. To format these on output to another timezone, use SimpleDateFormat. You can also associate a timezone with the value using a Calendar object:

java.util.Datejava.sql.Date类存储在UTC的实际时间(毫秒)。要将这些输出格式化为另一个时区,请使用SimpleDateFormat. 您还可以使用 Calendar 对象将时区与值相关联:

TimeZone tz = TimeZone.getTimeZone("<local-time-zone>");
//...
Date dateValue = rs.getDate("DateColumn");
Calendar calValue = Calendar.getInstance(tz);
calValue.setTime(dateValue);

Usefull Reference

有用的参考

https://docs.oracle.com/javase/9/troubleshoot/time-zone-settings-jre.htm#JSTGD377

https://docs.oracle.com/javase/9​​/troubleshoot/time-zone-settings-jre.htm#JSTGD377

https://confluence.atlassian.com/kb/setting-the-timezone-for-the-java-environment-841187402.html

https://confluence.atlassian.com/kb/setting-the-timezone-for-the-java-environment-841187402.html

回答by Eyal Schneider

I would retrieve the time from the DB in a raw form (long timestamp or java's Date), and then use SimpleDateFormat to format it, or Calendar to manipulate it. In both cases you should set the timezone of the objects before using it.

我会以原始形式(长时间戳或 java 的日期)从数据库中检索时间,然后使用 SimpleDateFormat 对其进行格式化,或使用 Calendar 对其进行操作。在这两种情况下,您都应该在使用对象之前设置对象的时区。

See SimpleDateFormat.setTimeZone(..)and Calendar.setTimeZone(..)for details

查看SimpleDateFormat.setTimeZone(..)Calendar.setTimeZone(..)了解详情

回答by Todd

I had to set the JVM timezone for Windows 2003 Server because it always returned GMT for new Date();

我必须为 Windows 2003 Server 设置 JVM 时区,因为它总是为 new Date() 返回 GMT;

-Duser.timezone=America/Los_Angeles

-Duser.timezone=America/Los_Angeles

Or your appropriate time zone. Finding a list of time zones proved to be a bit challenging also...

或您适当的时区。事实证明,查找时区列表也有点挑战性……

Here are two list;

这里有两个列表;

http://wrapper.tanukisoftware.com/doc/english/prop-timezone.html

http://wrapper.tanukisoftware.com/doc/english/prop-timezone.html

http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzatz%2F51%2Fadmin%2Freftz.htm

http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzatz%2F51%2Fadmin%2Freftz.htm

回答by snorbi

You could change the timezone using TimeZone.setDefault():

您可以使用TimeZone.setDefault()更改时区:

TimeZone.setDefault(TimeZone.getTimeZone("GMT"))

回答by MG Developer

Also if you can set JVM timezone this way

此外,如果您可以通过这种方式设置 JVM 时区

System.setProperty("user.timezone", "EST");

or -Duser.timezone=GMTin the JVM args.

-Duser.timezone=GMT在 JVM 参数中。

回答by lwpro2

for me, just quick SimpleDateFormat,

对我来说,只需快速 SimpleDateFormat,

  private static final SimpleDateFormat GMT = new SimpleDateFormat("yyyy-MM-dd");
  private static final SimpleDateFormat SYD = new SimpleDateFormat("yyyy-MM-dd");
  static {
      GMT.setTimeZone(TimeZone.getTimeZone("GMT"));
    SYD.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
  }

then format the date with different timezone.

然后用不同的时区格式化日期。

回答by bertan

create a pair of client / server, so that after the execution, client server sends the correct time and date. Then, the client asks the server pm GMT and the server sends back the answer right.

创建一对客户端/服务器,以便在执行后,客户端服务器发送正确的时间和日期。然后,客户端询问服务器 pm GMT,服务器将正确的答案发回。

回答by Incmos

If you would like to get GMT time only with intiger: var currentTime = new Date(); var currentYear ='2010' var currentMonth = 10; var currentDay ='30' var currentHours ='20' var currentMinutes ='20' var currentSeconds ='00' var currentMilliseconds ='00'

如果您只想使用整数获取 GMT 时间: var currentTime = new Date(); var currentYear ='2010' var currentMonth = 10; var currentDay='30' var currentHours='20' var currentMinutes='20' var currentSeconds='00' var currentMilliseconds='00'

currentTime.setFullYear(currentYear);
currentTime.setMonth((currentMonth-1)); //0is January
currentTime.setDate(currentDay);  
currentTime.setHours(currentHours);
currentTime.setMinutes(currentMinutes);
currentTime.setSeconds(currentSeconds);
currentTime.setMilliseconds(currentMilliseconds);

var currentTimezone = currentTime.getTimezoneOffset();
currentTimezone = (currentTimezone/60) * -1;
var gmt ="";
if (currentTimezone !== 0) {
  gmt += currentTimezone > 0 ? ' +' : ' ';
  gmt += currentTimezone;
}
alert(gmt)

回答by scot

Wow. I know this is an ancient thread but all I can say is do not call TimeZone.setDefault() in any user-level code. This always sets the Timezone for the whole JVM and is nearly alwaysa very bad idea. Learn to use the joda.time library or the new DateTime class in Java 8 which is very similar to the joda.time library.

哇。我知道这是一个古老的线程,但我只能说不要在任何用户级代码中调用 TimeZone.setDefault() 。这总是为整个 JVM 设置时区,而且几乎总是一个非常糟糕的主意。学习使用 joda.time 库或 Java 8 中新的 DateTime 类,它与 joda.time 库非常相似。

回答by Dawid St?pień

Use system property:

使用系统属性:

-Duser.timezone=UTC