Changing time and date in linux

Установка времени Linux

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

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

Как работает время на компьютере?

Статья ориентирована на новичков, в первую очередь на них, потому что профессионалы уже и так знают как это сделать. Поэтому сначала рассмотрим как работает время в Linux. Когда компьютер работает часы идут, это ясно, но когда вы его отключаете, а затем включаете снова часы показывают не то время, на котором остановились, а правильное время. Это происходит потому, что часы на материнской плате идут постоянно. Таймер питается от той же батарейки, что и энергозависимая память BIOS.

Операционная система передает значение таймера в память BIOS при выключении и берет его оттуда при включении. Отсюда берутся проблемы со временем при двойной загрузке Windows и Linux, но эта тема раскрыта в другой статье — сбивается время в Ubuntu и Windows. Другая проблема почему может сбиваться время — это неверно установленный часовой пояс. Если вы установили часовой пояс linux неверно, то часы будут постоянно синхронизироваться через интернет и идти неверно.

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

Установка времени Linux

Вы можете видеть текущее время прямо на вашем рабочем столе, в KDE часы добавлены на панель, да и в Gnome, они размещены по центру панели по умолчанию:

Если навести курсор на время, вы увидите более подробную информацию, область уведомлений и календарь.

Но настроить время здесь уже не получится. Для этого нужно открывать настройки системы. Мы будем рассматривать настройки для Gnome. Откройте меню Dash и наберите в строке поиска «Параметры»:

Дальше откройте «Дата и время»:

Как видите, здесь уже установлено значение по умолчанию «Автоматическое определение даты и времени», а внизу есть пункт, который отвечает за часовой пояс.

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

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

Установка времени через терминал

Кроме графического интерфейса, у вас есть возможность делать все необходимые действия через терминал. Для этого есть утилита date. Сначала смотрим текущее время:

Читайте также:  Определить uuid в linux

У утилиты есть множество опций отображения и настроек, но мы не будем их рассматривать. Есть еще одна команда, которая позволяет посмотреть системное время linux:

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

В качестве строки можно брать ту, которую возвращает команда date без параметров, только она должна быть на английском, поэтому сразу смотрим:

sudo date —set «Wed Sep 6 20:43:36 EEST 2017»

Если у вас включена коррекция даты через интернет, то ее нужно отключить перед этим, потому что вы даже заметить изменений не успеете, как сервер времени linux установит правильное время. Можно сократить эту строку:

sudo date —set «Sep 6 20:43:36 2017»

Это даст тот же результат. Еще один вариант — указать формат данных, которые вы собираетесь передавать с помощью модификаторов, например, изменить время linux:

Здесь формат очень прост — часы:минуты:секунды. Можно давать время в 12 часовом формате, для этого добавьте модификатор %p:

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

Еще один новый инструмент от systemd для управления временем — timedatectl. С помощью него можно выполнить те же операции, сначала смотрим доступную информацию о времени:

Текущее системное время отображается в строке Local Time. Чтобы изменить дату, используйте опцию -set-time. Синтаксис передаваемого ей параметра такой: ГГГГ-ММ-ДД ЧЧ:ММ:СС. Думаю тут понятно и без комментариев. Например:

sudo timedatectl —set-time «2017-09-06 20:43:36»

Можно задать только время, тогда нужно использовать синтаксис времени ЧЧ:ММ:СС, например:

sudo timedatectl —set-time «20:43:36»

Еще раз говорю, что если включена синхронизация по сети, то вы не сможете изменить время. Но с помощью timedatectl ее можно отключить:

sudo timedatectl set-ntp no

sudo timedatectl set-ntp yes

C помощью этой же команды можно не только установить время linux, но и настроить часовой пояс, для этого используйте опцию set-timezone:

sudo timedatectl set-timezone ‘Europe\Kyiv’

Вы можете посмотреть список доступных часовых поясов командой:

Видео о настройке времени с помощью timedatectl:

Выводы

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

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

Источник

How to Change Date, Time, and Time Zone in Linux Mint 20

Date, Time and Timezone

A time zone is identified based on the geographic region with the same standard time and date. Typically, the date, time, and time zone are set during the installation of an operational system. Users need to change the time zone for performing a few tasks in Linux platforms. Some jobs in Linux use time zone like cron jobs use it for execution or in logs timestamps. In this tutorial, we will go through different ways of changing the date, time, and time zone in Linux Mint 20 and Ubuntu 20.04.

To have the correct date and time in any operating system is very important since many operations depend on the date and time feature. To set a date, time in Linux Mint, open up the terminal either using the Ctrl+Shift+T shortcut or access it via ApplicationsTerminal.

Читайте также:  Freeipa astra linux smolensk установка

Change date in Linux from the command line

In Linux platforms, the server and the clock of the system need to be exactly on time. You need to have sudo rights privilege to make such changes in your computer system. To proceed, type the following command in the terminal window:

Set Date in Ubuntu

The output will appear as shown in the figure below and the date will be set based on the input value.

Date changed in Linux Mint

Check the updated date and time from command line

To check the updated time from the command line, simply type

Check the current date on the command line

The output will display the updated time field.

Date on Linux cmd

timedatectl is a utility of Linux that allows users to view the system’s time and date through the terminal. To view the current time, date and time zone, use:

timedatectl command

Change time in Linux from the command line

Users can also change the time from the command line by using

Set new date and time in Ubuntu

Here we have set the time to 15:14:00 and once we press the output will appear as shown below. The time will be updated accordingly.

Time changed successfully

Change date and time with one command on Ubuntu

Linux allows users to update date and time through one single command as well. To update date and time through the one common command, type the following:

Use a single command to change date and time

11: Hour (hh)
14: Minute (mm)
00: Second (ss)

As soon as you hit the key, the output will appear indicating that the date and time are updated accordingly.

Date and time changed

Set hardware clock in Linux

A hardware clock runs within the hardware of your computer system even if there is no power supply still it continues to function. To check out the hardware clock use the following command:

Show hardware clock time

The output will appear as shown in the figure below, displaying the time of the hardware clock.

Date and time as stored in hardware clock of the system

Now let’s check out the method that is used to set the hardware clock to the local time in a Linux system. For that, you will need to type:

$ hwclock --set --date="YYYY-MM-DD 16:45:05" --localtime

Set date and time in hardware clock

The hardware clock will be adjusted according to the local time.

Change the time zone through the command line

In order to change the time zone. First, let’s view the time zone of the system using timedatectl.

timedatectl command

The system time zone in a Linux Mint system is configured by symlinking which is a /etc/localtime file. It is further configured to the binary time zone identifier that exists in the /usr/share/zoneinfo directory.

Another way by which, users can check the available time zone by using:

Get time zone

The output will look like this:

Zone info

List of available time zones

To change the time zone, at first you need to find out and know the name of that time zone which you plan to use. Typically, the time zone in any system follows the “Region/City” format. Let’s view all available options.long name of the time zone you want to use:

$ timedatectl list-timezones

List time zones

The output will show a list similar to the one displayed below:

List of timezones

Now, you can use any of the option from the list to update the time zone. Use the following command:

$ sudo timedatectl set-timezone

Set time zone in Ubuntu

Here, in the example the time zone used by us is America/New_York. You can adjust the time zone as per your requirements following the same method.

Читайте также:  Linux узнать объем папок

Change the date, time, and time zone through GUI

To change the date, time and time zone through the UI method in Linux Mint 20, simply access the date and time shortcut on the bottom right of the screen and click on it. A calendar menu will open up, click on the Date and Time Settings option available at the bottom of the calendar.

Date and Time settings

You will see the Manually set date and Time option. Click on the date option against the Manually set date and time field.

A Select a Date modal will appear, you need to select a date then press the OK button to confirm the selection.

Select a date

To change the time, select the Time option against the Manually set date and time in the Date & Time menu.

Set time zone using GUI

A modal will appear as shown in the figure below, update the time then select OK to reflect changes.

Set time using GUI

To update the time zone, click on Region in date and time modal.

Choose Region

You will see a list of Regions available, select the region first. It will show possible cities for that selected region. You need to select a city to proceed, once done select OK to make changes.

Conclusion

The methods discussed in this tutorial, tell the ways to change the date, time, and time zone in Linux Mint 20. Users can change them either through the command line or through the UI based on their preference. Both methods are easy to implement and explained in detail in this tutorial with examples.

Источник

How to change ubuntu’s server date and time via command line?

The Ubuntu server’s current date and time is different from the time zone date and time. I have tried using:

sudo date "30 Sep 2015 4:43:42" 

to change it but it did not change the date and time, just printed on terminal the date and time I changed, but when I executed:

The date and time is still the old one. What is the correct way to change date and time of Ubuntu Server?

7 Answers 7

You can set the system date with this command:

sudo date --set="2015-09-30 10:05:59.990" 

Then when using date , it should be showed correctly.

Now you should also the set hardware clock in the BIOS of the system, that the setting persists over a reboot (dureing the startup the system time is set to the value of the hardware clock). Do that with hwclock :

This gets the system clocks (sys) value and sets the hardware clock (hc). Check it with the hwclock command. Both hwclock and date should now show the same date and time.

To set your timezone, you can use this command:

sudo dpkg-reconfigure tzdata 

BTW: If you use a this machine as a server, I strongly recommend using an NTP-Client to sync the time over network. So you can guarantee that all your servers have the exactly same time set. This will sync the time while the machine runs. If you have applications which are dependent of synced time over server, I recommend the NTP-Daemon. The longer it runs in the background, the more precise is the time.

Источник

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