Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java detect Time Zone after host OS default is modified

Tags:

java

timezone

I have a simple Java Executor thread running. This just detects the time zone and displays.

The code is as follows :

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {

            TimeZone.setDefault(null);
            //get Calendar instance
            Calendar now = Calendar.getInstance();

            //get current TimeZone using getTimeZone method of Calendar class
            TimeZone timeZone = now.getTimeZone();

            //display current TimeZone using getDisplayName() method of TimeZone class
            System.out.println("Current TimeZone is : " + timeZone.getDisplayName());
            System.out.println( System.getProperty( "user.timezone" ) );

      }
    }, 0, 10, TimeUnit.SECONDS);

The problem is, if I modify the time zone alone manually using the control panel.My time zone is not getting updated.

I have read a post explaining JVM time issue Java System.getProperty( "user.timezone" ) does not work

Now i need to detect system time zone change

like image 274
Sizen Avatar asked Oct 19 '16 10:10

Sizen


2 Answers

Given the latest comments, I have a workaround for you.

The problem is more or less: the JVM process will not notice when the timezone changes, so asking the JVM will not give you the information you need. That is why people suggest you to write some native (C/C++) code, and to call that from within the JVM to query Windows internals.

That should definitely work, but pulling together all the elements for this ... in a robust/correct way will be difficult (even for people beyond "beginner" level).

Thus, some other idea: do not use "native" code to query the time zone. Instead, you could be calling some script to do that; you grep its output and update your settings.

You could do that with python, or maybe directly with powershell.

So, your Java code would use a ProcessBuilder to run some command; and then you simply read from the outputstream of that process to fetch the string with the current (new) timezone.

Probably not the most robust solution in the world; but at least: quick to implement for some first testing.

Theoretically you could also try to run a Java class to print the timezone; that would have the nice advantage of getting the real Java name for the new Timezone for free!

Of course, the other aspect to keep in mind: you have to make sure that all your code is aware that the timezone can change!

like image 58
GhostCat Avatar answered Sep 21 '22 19:09

GhostCat


Executing the following code resets the time zone to the updated system value:

    System.setProperty("user.timezone", "");
    TimeZone.setDefault(null);
like image 29
Sizen Avatar answered Sep 22 '22 19:09

Sizen