Force Java timezone as GMT/UTC(强制 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
检索 Date/Time/Timestamp 对象时需要设置特定的时区,请使用 getXXX
方法的第二种形式,该方法采用 日历
对象:
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
类以 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:强制 Java 时区为 GMT/UTC


- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01