Linux set time terminal

How can I change the date and time on Ubuntu?

When I go to change the date and time it doesn’t work. I try to unlock but it just won’t unlock. If there is any way to make it work please help. I know it isn’t very descriptive but I really would appreciate some answers.

7 Answers 7

-s, --set=STRING set time described by STRING 

To change date, use the command in terminal,

For example, to change date to 25 Sep 2013 15:00, the command would be,

sudo date --set "25 Sep 2013 15:00:00" 

On 16.04 LTS, in Time & Date (System Settings), set the time manually. If not, the command is executed, but the date and the time are not changed.

not working. set date by sudo date —set=STRING result printed that date has changed but actually date is not changed.

sudo dpkg-reconfigure tzdata 

This both lets you configure your timezone (you may just pick the same), and automagically synchronizes your time.

If there’s no tzdata package, install it:

sudo apt-get update sudo apt-get install tzdata 

In 12.04 I don’t have to Unlock anything. Just click on the clock on the top bar, and choose Time & Date Settings, once the Time & Date window opens, choose Manually, so you can change the time and date manually; otherwise choose your time zone from the map, and choose Automatic.

enter image description here

enter image description here

I am not able to change my system’s time this way. I can change the time from the settings but it is not reflecting on my top bar.

You’ll have to change the focus of the Date spinner control to have the date changed immediately. Very odd 🙂 (Ubuntu 14.10)

sometimes to reflect the settings changes you need to kill unity panel service and restart it. Click clock on the top bar, and choose Time & Date Settings once the Time & Date window opens choose Manually so you can change the time and date manually; otherwise choose your time zone from the map, and choose Automatically. Now to reflect changes instantly open terminal and type killall unity-panel-service

Источник

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

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

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

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

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

Читайте также:  Astra linux smolensk обновление ядра

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

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

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

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

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

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

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

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

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

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

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

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

У утилиты есть множество опций отображения и настроек, но мы не будем их рассматривать. Есть еще одна команда, которая позволяет посмотреть системное время 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:

Читайте также:  What is linux partition table

Вы изменяете текущее время, но аппаратное системное время 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.

Источник

Linux: set date through command line

You can use e.g. date —set=’-2 years’ to set the clock back two years, leaving all other elements identical. You can change month and day of month the same way. I haven’t checked what happens if that calculation results in a datetime that doesn’t actually exist, e.g. during a DST switchover, but the behaviour ought to be identical to the usual «set both date and time to concrete values» behaviour.

Assuming you’re trying to set the date to the current time, you could do sudo ntpd -gq to have the system update automatically using the ntp service.

7 Answers 7

Run that as root or under sudo . Changing only one of the year/month/day is more of a challenge and will involve repeating bits of the current date. There are also GUI date tools built in to the major desktop environments, usually accessed through the clock.

To change only part of the time, you can use command substitution in the date string:

will change the date, but keep the time. See man date for formatting details to construct other combinations: the individual components are %Y , %m , %d , %H , %M , and %S .

There’s no option to do that. You can use date -s «2014-12-25 $(date +%H:%M:%S)» to change the date and reuse the current time, though.

@MichaelHomer @SHW it is possible to change only the date with a command like date -s 2018-01-01 . Someone shared this in an answer also: superuser.com/questions/870068/…

System time

You can use date to set the system date. The GNU implementation of date (as found on most non-embedded Linux-based systems) accepts many different formats to set the time, here a few examples:

date -s 'next year' date -s 'last year' 
date -s 'last month' date -s 'next month' 
date -s 'next day' date -s 'tomorrow' date -s 'last day' date -s 'yesterday' date -s 'friday' 
date -s '2009-02-13 11:31:30' #that's a magical timestamp 

Hardware time

Читайте также:  Добавить пользователя sftp linux

Now the system time is set, but you may want to sync it with the hardware clock:

Use —show to print the hardware time:

You can set the hardware clock to the current system time:

Or the system time to the hardware clock

Bonus points for illustrating the non-obvious ways you can set the date with examples and for pointing out the difference between the «system time» and the «hardware clock». Very helpful answer!

I think you confused hctosys and systohc. hctosys means «Set system time from hardware clock» and systohc means «Set hardware clock from system time».

The command to to change the system date is date .

There are two ways to call the date command(in Linux):

 date [OPTION]. [+FORMAT] date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]] 

Easy

The easiest way is to use date -s as it allows the use of simple relative dates

 $ date -s yesterday; date date: cannot set date: Operation not permitted Sat Jan 5 07:21:07 EST 2019 Sun Jan 6 07:21:07 EST 2019 

The date did not change because it was executed with a limited user $ . If you actually want the date changed, use root ( # ) or sudo:

 $ sudo date -s yesterday; date Sat Jan 5 07:21:07 EST 2019 Sat Jan 5 07:21:07 EST 2019 

So, changing any part of a relative date is as easy as naming it:

 $ date -s "5 years ago" Mon Jan 6 08:26:26 EST 2014 $ date -s "+6 months" Sat Jul 6 08:28:39 EDT 2019 $ date -s "+3 hours -13 minutes" Sun Jan 6 11:16:59 AST 2019 

Absolute dates are a bit more complex as they need more detail:

Or, you can use the date command twice:

replace any of the % by a valid value and the date will be set (only as root).

 $ date -s "$(date +'%Y-11-%d %H:%M:%S')" Wed Nov 6 08:37:15 EST 2019 

direct

The second date call form is used to directly change the system date.

 date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]] 

Will set the date to the 23th of November at 08h and 12min.

Try date as a limited user to see what it would do (without changing anything):

 $ date 11230812 date: cannot set date: Operation not permitted Sat Nov 23 08:12:00 EST 2019 

Or, if you actually want to change the date, as root:

 # date 11230812 # date Sat Nov 23 08:12:00 EST 2019 

Note that services like NTP or chrony will be affected. And, if restarted will reset the date back to the real one.

 $ date 1123081222 date: cannot set date: Operation not permitted Wed Nov 23 08:12:00 EST 2022 

Or a CCYY to set year and century:

 $ date 112308121982 date: cannot set date: Operation not permitted Tue Nov 23 08:12:00 EST 1982 

Источник

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