Force Java timezone as 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.
Thanks!
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>
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
}
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.
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);
Also if you can set JVM timezone this way
System.setProperty("user.timezone", "EST");
or -Duser.timezone=GMT
in the JVM args.
I had to set the JVM timezone for Windows 2003 Server because it always returned GMT for new Date();
-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://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzatz%2F51%2Fadmin%2Freftz.htm
链接地址: http://www.djcxy.com/p/29330.html上一篇: moment.js转换没有效果
下一篇: 将Java时区强制为GMT / UTC