How to ensure that java system property `user.timezone` is explicitly specified?



I want to be sure that my Java program is always run by explicitly specified user.timezone property. I pass -Duser.timezone=XXX as a command-line setting.

However, when I omit that system property at all, and then in my program I check the value of System.getProperty("user.timezone"), it is not null, instead, it contains the system timezone. So, I can’t terminate my program, as the value of that property is never null.

I know that I can use a custom system property name(say tz) to accept the timezone ID and then execute TimeZone.setDefault(System.getProperty("tz")) in my code, but I prefer to use the system property user.timezone, which is intended to be used for that reason.

Is there any way to achieve what I need using user.timezone system property ?

Answer

I very much agree with the answer by Basil Bourque: Your solution is to write your code so it is independent of a JVM default time zone. Also as mentioned in the comments, when using java.time types with your SQL database through JDBC 4.2 (or later), no default time zone interferes.

Furthermore from what I have read drivers tend to use the database session time zone, not the JVM default time zone. You may want to search your database documentation and your JDBC driver documentation for ways to control the session time zone.

However to answer your question as asked:

    String userTimezoneProp = System.getProperty("user.timezone");
    boolean timezonePropertyEmpty = userTimezoneProp == null || userTimezoneProp.isEmpty();
    if (timezonePropertyEmpty) {
        System.err.println("You must set the user.timezone property to the same time zone as the database time zone.");
        System.exit(-1);
    }

Only you must do this before doing any operations that use the default time zone. Once such an operation is performed, the JVM will query the operating system for a default time zone and set the system property accordingly (if successful).

According to the documentation System.getProperty() should return null for a system property that has not been set. My Java returned an empty string in this example. So I take both possibilities into account. It may be something special for user.timezone. I didn’t find any documentation mentioning it. I still do not guarantee that the method is bullet-proof.



Source: stackoverflow