I am using Java 7 on a Windows machine. I am developing a web app running on Tomcat.
I need to know the server's time zone. Here is what I do for this purpose:
TimeZone.getDefault();
Is this the correct way?
Thanks for your input!
Regards.
I am using Java 7 on a Windows machine. I am developing a web app running on Tomcat.
I need to know the server's time zone. Here is what I do for this purpose:
TimeZone.getDefault();
Is this the correct way?
Thanks for your input!
Regards.
TimeZone.getDefault()
Is this the correct way?
No, that class is now legacy, replaced by ZoneId
.
ZoneId.systemDefault()
But better if you specify your desired/expected zone rather than rely on JVM’s current default.
The modern solution uses the java.time classes (ZoneId
, ZoneOffset
, and ZoneRules
) rather than the troublesome old legacy date-time classes (TimeZone
).
You can ask for the JVM’s current default time zone.
ZoneId z = ZoneId.systemDefault() ;
But whatever purpose you have in mind is likely ill-advised. Firstly, best practice for servers is to set the host OS and the JVM’s default time zone to UTC. Secondly, you should never depend on the server’s time zone. That setting is out of your control as a programmer, and easily changed to an unexpected value. Within a JVM, any code in any thread of any app within that JVM may change the current default time zone during runtime.
Better to always specify your desired/expected time zone by passing an optional argument to the various java.time methods.
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "Africa/Tunis" ) ) ;
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
By the way, ditto for Locale
— always specify explicitly rather than rely implicitly on current default.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.