Java установить часовой пояс

Как установить часовой пояс JVM

Пользователи наших приложений могут быть требовательны к отметкам времени. Они ожидают, что наши приложения будут автоматически определять их часовые пояса и отображать метки времени в правильном часовом поясе.

В этом руководстве мы рассмотрим несколько способов изменения часового пояса JVM . Мы также узнаем о некоторых ловушках, связанных с управлением часовым поясом.

2. Введение в часовой пояс​

По умолчанию JVM считывает информацию о часовом поясе из операционной системы. Эта информация передается классу TimeZone , который хранит часовой пояс и вычисляет летнее время .

Мы можем вызвать метод getDefault, который вернет часовой пояс, в котором работает программа. Кроме того, мы можем получить список поддерживаемых идентификаторов часовых поясов из приложения, используя TimeZone.getAvailableIDs() .

При присвоении имени часовому поясу Java опирается на соглашение об именах базы данных tz .

3. Изменение часового пояса​

В этом разделе мы рассмотрим несколько способов изменения часового пояса в JVM.

3.1. Установка переменной среды​

Давайте начнем с того, как мы можем использовать переменную среды для изменения часового пояса. Мы можем добавить или изменить переменную окружения TZ.

Например, в среде на базе Linux мы можем использовать команду экспорта :

 export TZ="America/Sao_Paulo" 

После установки переменной среды мы видим, что часовой пояс нашего работающего приложения теперь Америка/Сан-Паулу:

 Calendar calendar = Calendar.getInstance();   assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("America/Sao_Paulo")); 

3.2. Установка аргумента JVM​

Альтернативой установке переменной среды является установка аргумента JVM user.timezone . Этот аргумент JVM имеет приоритет над переменной среды TZ .

Например, мы можем использовать флаг -D при запуске нашего приложения:

 java -Duser.timezone="Asia/Kolkata" com.company.Main 

Точно так же мы также можем установить аргумент JVM из приложения :

 System.setProperty("user.timezone", "Asia/Kolkata"); 

Теперь мы можем видеть, что часовой пояс — Азия/Калькутта:

 Calendar calendar = Calendar.getInstance();   assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("Asia/Kolkata")); 

3.3. Установка часового пояса из приложения​

Наконец, мы также можем изменить часовой пояс JVM из приложения с помощью класса TimeZone . Этот подход имеет приоритет как над переменной среды, так и над аргументом JVM.

Установить часовой пояс по умолчанию очень просто:

 TimeZone.setDefault(TimeZone.getTimeZone("Portugal")); 

Как и ожидалось, часовой пояс сейчас Португалия :

 Calendar calendar = Calendar.getInstance();   assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("Portugal")); 

4. Подводные камни​

4.1. Использование трехбуквенных идентификаторов часовых поясов​

Хотя можно использовать трехбуквенные идентификаторы для обозначения часового пояса, это не рекомендуется .

Вместо этого мы должны использовать более длинные имена, так как трехбуквенные идентификаторы неоднозначны. Например, IST может быть стандартным временем Индии, стандартным временем Ирландии или стандартным временем Израиля.

4.2. Глобальные настройки​

Обратите внимание, что каждый из вышеперечисленных подходов устанавливает часовой пояс глобально для всего приложения. Однако в современных приложениях настройка часового пояса часто более тонкая.

Например, нам, вероятно, нужно перевести время в часовой пояс конечного пользователя, поэтому глобальный часовой пояс не имеет особого смысла. Если глобальный часовой пояс не нужен, рассмотрите возможность указания часового пояса непосредственно в каждом экземпляре даты и времени. Для « этого удобен класс ZonedDateTime или OffsetDateTime .

5. Вывод​

В этом руководстве мы объяснили несколько способов изменения часового пояса JVM. Мы увидели, что можем либо установить общесистемную переменную среды, либо изменить аргумент JVM, либо изменить его программно из нашего приложения.

Как обычно, все примеры, использованные в этой статье, доступны на GitHub.

Источник

How to Set the JVM Timezone

Learn to set the default time zone used by the JVM using an environment variable, JVM argument and TimeZone class.

The users of any application want to see the dates and timestamps in their local timezone, and nobody likes to make timezone adjustments in their mind.

To show local date timestamps to users, the timezone used by the JVM must be predictable and preferably fixed. It makes the application’s unit testing and integration testing, concerning timezone-specific timestamps, easy and more reliable.

Setting the JVM time zone is more necessary in the distributed deployment models where the application is running across multiple data centers around the globe, and JVMs in each data center can be a different time zone.

  • By default, the JVM reads time zone information from the operating system and stores it in the TimeZone class.
  • To get the default time zone set in the JVM using the method TimeZone.getDefault() .
  • To get the list of all supported timezones, use the method TimeZone.getAvailableIDs() .
  • Java uses the naming convention of the tz database.

2. How to Set the Timezone for JVM

2.1. Set Environment Variable ‘TZ’

Set the environment variable TZ that JVM can use to get the default time zone in the JVM.

In Linux, we can use export command.

In windows, we can set the time zone as discussed using the Control Panel -> Date and Time -> Change Time Zone -> Select your preferred time zone option.

After setting the environment variable, we can verify it in our Java program.

TimeZone timezone = TimeZone.getDefault(); System.out.printf("DisplayName = %s, offset = %s", timeZone.getDisplayName(),timeZone.getID(),timeZone.getRawOffset());
DisplayName = Coordinated Universal Time, offset = 0

2.2. Set JVM Argument or System Property ‘user.timezone’

If setting the environment variable is not possible then we can set the time zone using the JVM argument -Duser. timezone . Do not enclose the timezone value in double-quotes.

java -Duser.timezone=UTC com.app.Main //or java -Duser.timezone=Asia/Kolkata com.app.Main 

The same argument, we can set using the system property «user.timezone» .

System.setProperty("user.timezone", "UTC");

Now we can verify the updated timezone value in the Java programs.

TimeZone timezone = TimeZone.getDefault(); System.out.printf("DisplayName = %s, offset = %s", timeZone.getDisplayName(),timeZone.getID(),timeZone.getRawOffset());
DisplayName = Coordinated Universal Time, offset = 0

Another way similar to setting system property is by setting the default time zone directly in the TimeZone class.

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

Verifying the timezone value will give the same result as in the previous techniques.

3. How JVM Resolves the Timezone

By default, Java Date and Time classes pick the time zone information from the operating system. The way, JVM resolves OS timezone, is different in each operating system.

One way to get the machine time zone is from the system clock and modify the desired timezone in the clock. But this approach is not possible in the cloud environment where resources are made available on demand.

We can alter the value of the timezone with the runtime JVM arguments and Java statements in the application.

  • The TZ environment variable, if available, overrides the system’s default timezone.
  • JVM argument -Duser.timezone overrides TZ environment variable.
  • TimeZone.setDefault() overrides the -Duser.timezone argument.
  • Never rely on the default zone of the machine. Always specify your desired/expected time zone using one of the above-mentioned techniques.
  • An application can have time zone sensitive timestamps where after deploying the application in a cloud environment, the application could be moved to different data centers without our knowledge. To avoid these inconsistencies, it is recommended to set the JVM time zone using the -Duser.timezone system property.
  • If our requirement is to use a timezone not only by the JVM but also for all of its child processes, such as IDEs, then setting the TZ environment variable makes more sense. A good example of it is to set this variable when starting Eclipse and then you have it in all JVMs started by Eclipse.
  • We should prefer to use the longer names of the timezones instead of the three-letter IDs. There are short IDS that are duplicated among multiple time zones. For example, IST could be either India Standard Time, Irish Standard Time or Israel Standard Time.

In this tutorial, we learned to set the default time zone used by JVM in Unix and Windows operating systems.

As a best practice, always set the default timezone either at the JRE level or the application level to get consistent and expected timestamps.

Источник

Читайте также:  Символьный тип данных питон
Оцените статью