强制Java时区为GMT / UTC [英] Force Java timezone as GMT/UTC

查看:281
本文介绍了强制Java时区为GMT / UTC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

为了澄清,我正在使用数据库服务器时间进行所有操作,但它是根据当地时区格式化的。

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

谢谢!

推荐答案

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

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

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

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

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

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

或者,设置日期为一个PreparedStatement:

Or, setting the date in a 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.

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

The java.util.Date and java.sql.Date classes 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:

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

有用参考

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

这篇关于强制Java时区为GMT / UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆