Linux setting the timezone

Как изменить часовой пояс в Linux

Часовой пояс в Linux обычно настраивается во время установки системы. Иногда пользователю может потребоваться его изменить. Способ изменения часового пояса (его еще называют временной зоной) может зависеть от конкретного дистрибутива. Рассмотрим некоторые из способов изменения часового пояса.

Посмотреть текущий часовой пояс

Посмотреть текущий часовой пояс можно разными способами.

Команда date

Команда date выводит текущую дату, время и часовой пояс:

В выводе команды мы можем видеть, что текущая временная зона соответствует Москве — MSK .

Команда timedatectl

Утилита timedatectl применяется для настройки и получения информации о текущем системном времени. Она доступна в системах, использующих systemd.

Если выполнить команду timedatectl без параметров, то будет выведена информация о системных часах, а также часовой пояс (в поле Time zone ).

ls -lh /etc/localtime

Файл /etc/localtime это символическая ссылка, которая указывает на текущий часовой пояс, используемый в системе.

Для просмотра можно воспользоваться командной:

Получить список доступных часовых поясов

Утилита tzselect

Перед тем, как устанавливать часовой пояс, нужно понять, какое значение можно установить. Для этого можно воспользоваться утилитой tzselect .

После запуска утилита tzselect отображает список географических областей. Вы должны ввести номер области и нажать Enter . Затем появится список стран. Аналогично, нужно ввести номер страны. Появится список городов. Вводим номер города. В результате вы сможете увидеть название вашей временной зоны.

Утилита timedatectl

Утилита timedatectl поддерживает опцию list-timezones . Выполнив следующую команду можно просмотреть список всех доступных временных зон:

Можно воспользоваться grep и ограничить область поиска. Например, выведем список временных зон только для Европы:

Изменить часовой пояс

Изменяем часовой пояс утилитой timedatectl

Напомним, что утилита timedatectl доступна только для систем, использующих systemd. Если у вас нет утилиты timedatectl, то используйте способ описанный в следующем параграфе.

Для установки часового пояса с помощью утилиты timedatectl нужно выполнить команду:

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

Изменяем часовой пояс настройкой /etc/localtime

Данный способ наиболее универсальный и работает в большинстве дистрибутивов Linux.

Необходимо создать символическую ссылку /etc/localtime , чтобы она указывала на файл нужной временной зоны. Файлы временных зон хранятся в каталоге /usr/share/zoneinfo/ . Каждая зона имеет путь /usr/share/zoneinfo/Название/Зоны . Например, для Москвы это /usr/share/zoneinfo/Europe/Moscow .

Итак создадим ссылку на нужный файл временной зоны:

Чтобы проверить, что временная зона установлена верно, можно выполнить команду date :

Изменить часовой пояс только для одной программы или текущей сессии

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

Чтобы установить часовой пояс только для текущей сессии в терминале, используется команда:

Изменить часовой пояс через графические утилиты

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

Если вы работаете в Gnome, откройте Параметры системы .

Перейдите на вкладку Сведения о системе , далее вкладка Дата и время (в зависимости от версии Gnome названия пунктов могут немного отличаться). Нажмите на надпись Часовой пояс .

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

Заключение

Мы рассмотрели как изменить часовой пояс в Linux, как определить текущий часовой пояс и просмотреть список доступных временных зон. Большинству пользователей подойдет способ с использованием графической программы для изменения Параметров системы.

Источник

Как изменить часовой пояс Linux

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

Наша планета разделена на часовые пояса, это было сделано с одной простой целью, чтобы время в любой точке планеты соответствовало солнечному времени. Время между этими зонами отличается на час и всего таких поясов — 24, за эталон взято время по нулевому, Гринвичскому меридиану.

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

Как работает время в Linux?

Операционная система Linux хранит и обрабатывает системное время в специальном Unix формате — количество секунд прошедших с полуночи первого января 1970 года. Эта дата считается началом эпохи Unix. И используется не ваше локальное время, а время по гринвичскому меридиану.

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

Читайте также:  Прозрачный терминал linux mint

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

Настройка часового пояса в linux

1. Ссылка /etc/localtime

Наиболее популярный и поддерживаемый в большинстве дистрибутивов способ установки часового пояса для всех пользователей — с помощью символической ссылки /etc/localtime на файл нужного часового пояса. Список доступных часовых поясов можно посмотреть командой:

Сначала создайте резервную копию текущего часового пояса:

cp /etc/localtime /etc/localtime.bak

Для создания символической ссылки используйте команду ln -sf. Файл зоны нужно выбрать из доступных в системе. Например, мой часовой пояс — Украина, Киев, для установки будет использоваться следующая команда:

ln -sf /usr/share/zoneinfo/Europe/Kiev /etc/locatime

Теперь можете проверить текущее системное время с помощью утилиты date:

Если у вас установлена утилита rdate можно синхронизировать время с сетью:

sudo rdate -s time-a.nist.gov

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

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

Эта настройка сохраняется только для текущего сеанса командной оболочки. Чтобы сменить часовой пояс linux для определенного пользователя тоже нужно использовать переменную среды TZ. Только ее нужно добавить в файл

/.environment. Этот файл читается по умолчанию при входе в систему, а значит переменная будет доступна всем программам:

Готово, теперь вы знаете как выполняется настройка часового пояса linux для определенного пользователя.

2. Настройка с помощью tzdata

Если вы не хотите использовать описанный выше способ, можно воспользоваться специальными утилитами. Вот только в разных дистрибутивах используются свои утилиты. Рассмотрим варианты для самых популярных дистрибутивов.

В Red Hat Linux:

В CentOS и Fedora:

В Slackware или FreeBSD:

В большинстве случаев вы увидите подобное диалоговое окно:

Здесь просто нужно выбрать нужный часовой пояс и нажать кнопку Enter. После этого для окончательного применения настроек нужно будет перезагрузить систему.

3. Настройка с помощью systemd

В systemd есть своя утилита для настройки даты и часового пояса. Чтобы узнать текущее состояние выполните:

Для просмотра всех доступных временных зон выполните такую команду:

А для установки нужного часового пояса используйте команду set-timezone, например, тот же Europe/Kiev:

sudo timedatectl set-timezone Europe/Kiev

4. Настройка часового пояса в GUI

В дистрибутиве Ubuntu и других, использующих Gnome, настройка часового пояса Linux может быть выполнена прямо в параметрах системы. Для этого выберите пункт Сведения о системе, затем Дата и время, выберите свое местоположение на карте, или наберите название для поиска в поле ввода:

В KDE аналогично можно установить часовой пояс в настройках системы. Запустите утилиту настроек, откройте пункт Локализация, перейдите в раздел Дата и время, а затем откройте вкладку Часовой пояс:

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

Выводы

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

На завершение видео, в котором подробно рассказано, что такое часовые пояса и зачем они нужны:

Источник

HowTo: Linux Server Change OR Setup The Timezone

M y Linux systems timezone is pointing to the wrong timezone. How do I setup or change the timezone under Linux operating systems?

Unix time, or POSIX time, is a system for describing points in time: it is the number of seconds elapsed since midnight UTC on the morning of January 1, 1970, not counting leap seconds. The definition for time zones can be written in short form as UTC±n (or GMT±n), where n is the offset in hours. You can use the following commands:

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements None
Est. reading time N/A

Command to change the Linux timezone

You need to type the following commands as per your Linux distribution.

If you are using Fedora / RHEL / Cent OS Linux

Type the redhat-config-date command at the command line to start the time and date properties tool, run:
# redhat-config-date
OR type setup and select time zone configuration. This tool is recommended for remote ssh text based sessions.
# setup
Select timezone configuration

Fig.01: Redhat / CentOS Server Setting Up Timezone

If you are using Debian / Ubuntu Linux

To change the timezone for you run the following command as root user:
# dpkg-reconfigure tzdata
Again, just follow on screen instructions.

Set timezone using /etc/localtime configuration file [any Linux distro]

Often /etc/localtime is a symlink to the file localtime or to the correct time zone file in the system time zone directory.

Generic procedure to change timezone under Linux

Cd to /etc, run:
# cd /etc
Create a symlink to file localtime:
# ln -sf /usr/share/zoneinfo/EST localtime
OR some distro use /usr/share/zoneinfo/dirname/zonefile format (Red hat and friends):
# ln -sf /usr/share/zoneinfo/EST localtime
OR if you want to set up it to IST (Asia/Calcutta):
# ln -sf /usr/share/zoneinfo/Asia/Calcutta localtime
Please note that in above example you need to use directory structure i.e. if you want to set the timezone to Calcutta (India) which is located in the Asia directory.

How do I verify new settings?

Use the date command to verify that your timezone is changed:
$ date
Output:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

How do I use of environment variable called TZ?

You can use TZ environment variable to display date and time according to your timezone:
$ export TZ=America/Los_Angeles
$ date

Sample Output:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

On Ubuntu you can do

tzconfig

to select and set the time zone.
(tzconfig copies the right time zone file from /usr/share/zoneinfo to /etc/localtime and puts the name of the timezone into /etc/timezone)

tzconfig is deprecated, use without “dpkg-reconfigure tzdata”

Opps! I mean use without quotes 🙂

Counterintuitively, you should not symlink, only ever copy timezone data files. This is because some programs might attempt to alter /etc/localtime. Before you make a change, notice that /etc/localtime is a regular file.

Note – you’re missing an ‘e’ on the end of:
Create a symlink to file localtime:
# ln -sf /usr/share/zoneinfo/EST localtim

Thanks for pointing out a typo. The faq has been updated.

I don’t get to change the TZ. I cann’t install the tzconfig. I have Ubuntu 8.04. What is wrong ?

Hey.. thanks.. it saved my life..

]# date
Tue Dec 2 10:19:11 UTC 2008

Using the “setup” command, I selected timezone as Asia/Calcutta, and did not check the UTC box. But the time zone does not change.

]# date
Tue Dec 2 10:20:26 UTC 2008

Also, I did the sym-link for localtime, but without help.

]# ls -l /etc/localtime
lrwxrwxrwx 1 root root 33 Dec 2 10:16 /etc/localtime -> /usr/share/zoneinfo/Asia/Calcutta

On CentOS5, the command is system-config-date. Likely on CentOS4 and earlier as well. Probably related to removing all branding from the upstream vendor’s sources.

Thanks! (system-config-date) That worked.

use tzselect for ubuntu gutsy

1.Iam having a linux virtual machine running apache server in RHEL4.4. Iam facing a problem that everyday in the morning I had to change its date and time . It is always running 12hrs back.

Use an NTP cronjob to update your time

1. iam also facing problem in RHJEL 5.2 virtualization. Iam having one host machine installed with RHEL 5.2. Iam also running 03 Server Virtually on it. But via network i can access virtual machine but not the host machine. Many tinme I had to restart the network service but after some time the problem exist. The service is also put under chkconfig.

2. Iam having a linux virtual machine running apache server in RHEL4.4. Iam facing a problem that everyday in the morning I had to change its date and time . It is always running 12hrs back.

Thanks a lot. This really helped me.

On CactiEZ 0.6 (based on CentOS) the command is ‘tzselect’ too.
No more system-config-date or ‘config’

Slackware dudes, use tzselect;

Or simply create a symbolic link called

from the suitable zones resides in /usr/share/zone

Thanks buddy, it helped me a lot!!

Does anybody know what can be done on SUSE if this does not work for some TZ? UTC works for example, but setting to Europe/Berlin or GB does not. These give back an empty value when using

RHEL 5 is also using tzselect as the command name.

OH MY GAD! Thank you for this article. I searched a long time to find this solution that finally worked. I use proxmox and this was the only thing that did it.

Thanks budy ,
I have same issue which has been resolved with help of you guys

Hai…
My Hp-ux server showing wrong time …so how can i change it…
hp-ux server:HP-UX B.11.11 U 9000/800 941485843 unlimited-user license
and if i change hp-ux server is it change in oracle database also..

How to change the TimeZone of the server based in London but it has same TZ as Paris.
We have Linux server.
Using command line and which files to be modified.

Can any one help me out for the above.

FYI, on Ubuntu 10.04, I also thought it was necessary to manually maintain /etc/localtime, /etc/timezone and friends to change to Asia/Calcutta. But I noticed when running “dpkg-reconfigure tzdata” that Asia/Kolkata does show up, and this is the same city/timezone. redhat-config-date might do something similar, I don’t know.

/usr/share/zoneinfo/Asia/Calcutta and /usr/share/zoneinfo/Asia/Kolkata point to the same inode on my system.

It works. Thanks a lot.

Thanks a bunch. I found this extremely useful to set my Server time to Indian TimeZone.

It worked thanks a lot

using fedora… “rm /etc/localtime” first and then make the link , worked for me.

Now amsn works fine and my local time now its right.

I mistakenly typed in date -u now it always shows date in UTC time, everytime I type date. I want the date to revert back to showing PST time when I type date.
How do I revert back for date to just PST time agan.

Don’t use “system-config-date” if you have build the symbolic link like

[root zoneinfo]# ls -l /etc/localtime
lrwxrwxrwx 1 root root 23 Jan 20 13:43 /etc/localtime -> /usr/share/zoneinfo/GMT

It could corrupt your original file “/usr/share/zoneinfo/GMT”

I was puzzling weeks on it to find out that my original files were corrupted.
I got that hint from another thread out there.

For Debian/Ubuntu, you have to edit

and locate your city in (relative) directory/file tree, i.e. Europe/Athens; put this exact string in

I tried to configure timezone on CentOS with VMware,

ln -s /usr/share/zoneinfo/Asia/Jakarta /etc/localtime

and the results were successful, but there are differences in time with my computer. I am confused where lies the problem, please help, thx before

In Arch, simply edit /etc/rc.conf and modify TIMEZONE.
it sould be the relative path to the zoneinfo file in /usr/share/zoneinfo
for example to set your local time to New York:
> cd /usr/share/zoneinfo/
> find . -name New_York
./America/New_York

now edit rc.conf:
TIMEZONE=”America/New_York”

I want it to work for ‘UBUNTU’.
Please help.

So after I use the /etc/localtime method sure if I type date the response from date is in the right timezone, but what about every running task, they are still using the old timezone. examples are crontab, mysqld, etc… obviously booting the system does ensure everything changes over, and cycling crontab for example fixes it, but is their a easy way to sync all without an outage.

Dear Vijay,
My Linux mechines are running under vmware server. My server time is changed every day. I reset my time every date with date -s command. But my windows mechines are running good. Time variation between linux and windows varied. Every day morning my clock shows 09:00 o clock but my server shows 09:50 or 10:00 or 10:03…. How do i set my linux box time constantly

can you help change time zone for linux suse

It works for ubuntu/kubuntu also. Thanks a lot.

Thanks! The ln method worked fine on FC14.
I noticed that some things (httpd) do not pick up the change until restarted.

I running shell script in Ec2-amazon web service.I dont want to change the time zone of server rather wanted to know with some command if I can get IST time.By default it shows UTC .I think if we pass some parameter with date command ,it should work. Please help me out .

really a valuable information……………Thanks for that piece.

Setting timezone via /etc/localtime worked fine in CentOS 6!

Are restarts usually required for any Linux distro for the timezone change to
truly occur?

i use Malaysia time zone.

how to change it to MYT?

I just wanted to shed some light on troubleshooting a time setting issue when rebooting.

The /etc/rc.sysinit file sets the system time (on bootup) based on the settings in /etc/sysconfig/clock. If UTC is set to true, it will set the system time based on this command:

If “hwclock –utc” shows a different time than “date”, that may mean the hardware clock is set using local time instead of UTC.

So you can clearly see that the time is set using local time and not UTC.

Here is the step by step fix:
1. login to server
2. type “date” to check the date/timezone
3. type “setup” and then choose “Timezone Configuration” to choose the correct timezone (GMT -3)
4. type “date” to check if it took
5. if time is incorrect, type “date MMDDhhmm” (ex. date 05230416)
6. change UTC=false in /etc/sysconfig/clock
7. sync hardware clock “hwclock –systohc”

I hope this was as helpful to you as it was to me.

It’s a good idea to restart syslog after changing the timezone, so it picks up the change.

For CentoS timezone select command: tzselect

You are written “Please mote that” instead of “Please note that” 🙂

Thank you! Worked well with Ubuntu 12.04. Had to restart apache2 and rsyslog (as noted in an earlier comment).

you always have the solution ready for all my linux related problems. this site really empowers me to self-manage my budget vps without having to pay $$$.

Источник

Читайте также:  Ustanovka windows na ssd
Оцените статью