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!
You can explicitly set a default time zone on the command line by using the Java system property called user. timezone . This bypasses the settings in the Windows operating system and can be a workaround.
SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); f. setTimeZone(TimeZone. getTimeZone("UTC")); System.
Prior to 1972, this time was called Greenwich Mean Time (GMT) but is now referred to as Coordinated Universal Time or Universal Time Coordinated (UTC). It is a coordinated time scale, maintained by the Bureau International des Poids et Mesures (BIPM). It is also known as "Z time" or "Zulu Time".
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);
Usefull Reference
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
Also if you can set JVM timezone this way
System.setProperty("user.timezone", "EST");
or -Duser.timezone=GMT
in the JVM args.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With