Change timezone linux terminal

Setting timezone from terminal

«which will set to gmt» But is there a way to set time zone with just the offset ie.-1 or +5 etc? I need to do this as I’m writing an application to adjust timeoffset or report logs and the only info I have is the user IP. I can use a webapp to find the location of the IP, but then I need to set offset which would be easy IF I could just get the offset of the location, but if I need to find zone and city it would be a real pain. If anyone knows the answer to how to set system clock with +/-hour would be great.

Please help us to pick up the accepted answer. I think @Mitch’s answer is the best askubuntu.com/a/323163/22308

@NamGVU No, Mitch’s is not the best solution, it’s a «GUI in a terminal» answer. Even the OP said » this wont work as i need to altr timezone from a program without user input i need a command i can feed into terminal not gui solution», and that’s the same objective most would want when looking for a «terminal solution,» a script-friendly one. Collin Anderson’s is better if you know a city, or Ryan’s for plain GMT+-n

8 Answers 8

To change time zone from terminal, just press Ctrl + Alt + T on your keyboard to open Terminal. When it opens, run the command(s) below:

sudo dpkg-reconfigure tzdata 

Once open, just follow the screens to change the time zone.

this wont work as i need to altr timezone from a program without user input i need a command i can feed into terminal not gui solution thanks for reply

thx. this helps, byt i’m already changed manually etc/timezone =) like php.net/manual/en/timezones.php . absolutely identical .

Reconfiguring tzdata seems to adjust the hardware clock too so that the displayed time stays the same after the time zone switch. You might want that if your time was correct but time zone was wrong. However you definitely don’t want to touch your hardware clock while traveling. The timedatectl approach seems to change time zone only.

You can also use the new timedatectl to set the time in 14.04.

sudo timedatectl set-timezone America/New_York 

To see all available options, you can run ls -R —group-directories-first /usr/share/zoneinfo . (Be careful not to modify or erase any file here.) More info about posix and right prefixes is here.

I realize this thread is a bit dated, but I was looking for a better solution because I needed to automatically set the timezone in a VM after a user downloads it from our website and deploys it. Here’s what I ended up with:

echo "Setting TimeZone. " export tz=`wget -qO - http://geoip.ubuntu.com/lookup | sed -n -e 's/.*\(.*\).*/\1/p'` && timedatectl set-timezone $tz export tz=`timedatectl status| grep Timezone | awk ''` echo "TimeZone set to $tz" 

This will query geoip.ubuntu.com from the server once it is started on the new network (my script checks for connectivity first course) and then set the server’s timezone based on the response.

Читайте также:  Format all partitions linux

The «wget -q0 -» tells wget to output only the results to stdout which is then piped to the $tz variable.

Источник

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

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

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

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

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

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

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

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

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

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

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

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

cp /etc/localtime /etc/localtime.bak

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

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

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

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

Читайте также:  Linux create partition on disk

sudo rdate -s time-a.nist.gov

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

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

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

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

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

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

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

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

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

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

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

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

sudo timedatectl set-timezone Europe/Kiev

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

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

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

timezone1

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

Выводы

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

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

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to Set or Change Timezone in Ubuntu Linux [Beginner’s Tip]

When you install Ubuntu, it asks you to set timezone. If you chose a wrong timezone or if you have moved to some other part of the world, you can easily change it later.

How to change Timezone in Ubuntu and other Linux distributions

There are two ways to change the timezone in Ubuntu. You can use the graphical settings or use the timedatectl command in the terminal. You may also change the /etc/timezone file directly but I won’t advise that.

Читайте также:  Qt charts astra linux

I’ll show you both graphical and terminal way in this beginner’s tutorial:

How to Change Time Zone in Ubuntu

Method 1: Change Ubuntu timezone via terminal

Ubuntu or any other distributions using systemd can use the timedatectl command to set timezone in Linux terminal.

You can check the current date and timezone setting using timedatectl command without any option:

[email protected]:~$ timedatectl Local time: Sat 2020-01-18 17:39:52 IST Universal time: Sat 2020-01-18 12:09:52 UTC RTC time: Sat 2020-01-18 12:09:52 Time zone: Asia/Kolkata (IST, +0530) System clock synchronized: yes systemd-timesyncd.service active: yes RTC in local TZ: no

As you can see in the output above, my system uses Asia/Kolkata. It also tells me that it is 5:30 hours ahead of GMT.

To set a timezone in Linux, you need to know the exact timezone. You must use the correct format of the timezone (which is Continent/City).

To get the timezone list, use the list-timezones option of timedatectl command:

timedatectl list-timezones

It will show you a huge list of the available time zones.

Timezones In Ubuntu

You can use the up and down arrow or PgUp and PgDown key to move between the pages.

You may also grep the output and search for your timezone. For example, if you are looking for time zones in Europe, you may use:

timedatectl list-timezones | grep -i europe

Let’s say you want to set the timezone to Paris. The timezone value to be used here is Europe/Paris:

timedatectl set-timezone Europe/Paris

It won’t show any success message but the timezone is changed instantly. You don’t need to restart or log out.

Keep in mind that though you don’t need to become root user and use sudo with the command but your account still need to have admin rights in order to change the timezone.

You can verify the changed time and timezone by using the date command:

[email protected]:~$ date Sat Jan 18 13:56:26 CET 2020

Method 2: Change Ubuntu timezone via GUI

Press the super key (Windows key) and search for Settings:

Applications Menu Settings

Scroll down a little and look for Details in the left sidebar:

Settings Detail Ubuntu

In Details, you’ll fine Date & Time in the left sidebar. Here, you should turn off Automatic Time Zone option (if it is enabled) and then click on the Time Zone:

Change Timezone In Ubuntu

When you click the Time Zone, it will open an interactive map and you can click on the geographical location of your choice or type the city name. Once you have selected the correct timezone, close the window.

Set Timezone In Ubuntu

You don’t have to do anything other than closing this map after selecting the new timezone. No need to logout or shutdown Ubuntu.

I hope this quick tutorial helped you to change timezone in Ubuntu and other Linux distributions. If you have questions or suggestions, please let me know.

Источник

Оцените статью
Adblock
detector