System date in linux

Display Date And Time In Linux

H ow do I display date and time in Linux using the command line and GUI options?

To display date and time under Linux operating system using command prompt use the date command. It can also display the current time / date in the given FORMAT. We can set the system date and time as root user too.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux with the terminal application
Est. reading time 3 minutes

Syntax

Open a terminal and type the following command:
date

You can format the date as follows in dd-mm-yy format:
date +»%d-%m-%y»

Simply display the current time:
date «+%T»

  • 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

To print the date of the day before yesterday, run:
date —date=’2 days ago’
Want to see the day of year of Christmas in the current year? Try:
date —date=’25 Dec’ +%j
Display the current full month name and the day of the month:
date ‘+%B %d’

Display date and time in Linux using the timedatectl

Most modern Linux distro with systemd use the timedatectl command. It is used to query and change the system clock and its settings, and enable or disable time synchronization services. All you have to do is type the following command:
$ timedatectl

TZ environment variable

The TZ environment tells Linux what time zone you are in. Many times when you want to change your time zone temporarily. For example, you might want to print the current date and time in “America/Los_Angeles” timezone even though you are in “Europe/London”. So we can set TZ, give a command like as follows when using TCSH/CSH:
setenv TZ timezone
For BASH/KSH/SH (see export command:
TZ=timezone; export TZ
Another option:
TZ=»America/Los_Angeles» date
TZ=»Asia/Tokyo» date
Use the following command to print a list of all timezones:
timedatectl list-timezones
timedatectl list-timezones | more
## filter out data using the grep command/egrep command ##
timedatectl list-timezones | grep -i Hong_kong
timedatectl list-timezones | grep -i paris
timedatectl list-timezones | grep -E -i ‘paris|london|kolkata’

The TZ Environment Variable on Linux

GUI Tool: Time Administration

The Time Administration Tool allows you to set the time, date and timezone of your system, as well as setting any time server to synchronize your local time server. Type the following command to start time admin tool:
sudo time-admin
## OR ##
time-admin

Fig.01: Linux Date and Time Administration Tool

How to change date and time settings with Gnome based Linux desktop

First, you need to Settings in Activities and then click Details in the sidebar. Make sure you click Date & Time in the sidebar to open the panel:

Conclusion

In this quick tutorial, you learned about the date command that you can use to see or change the date/time under Linux operating systems. We further explained how to use the GUI tools too. The date command has many more options. See man page by typing the following man command:
$ man date

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

Источник

Команда date в Linux

Главное свойство утилит GNU/Linux — делать что-то одно, но эффективно. Яркий пример — команда date Linux, работающая с датой и временем. С её помощью можно извлекать любую дату в разнообразном формате, в том числе и рассчитывать прошлое и будущее время. Привилегированные пользователи могут перезаписывать системное время, используя её.

Утилита предустановлена во всех дистрибутивах GNU/Linux. В этой статье будут рассмотрены возможности date и способы применения этой команды.

Синтаксис команды date

Программа может выполнятся от имени обычного пользователя. Стандартный синтаксис команды (квадратные скобки обозначают необязательное наличие):

date [ ОПЦИИ ] . [ +ФОРМАТ ]

Ниже представлена таблица с часто применяемыми опциями для date.

Опция Длинный вариант Значение
-d STRING —date=STRING Вывод даты по указанной строке (например ‘yesterday’, ‘tomorrow’, ‘last monday’).
-I —iso-8601[=FMT] Вывод даты в формате ISO 8601. FMT по умолчанию содержит ‘date’. Также может содержать ‘hourse’, ‘minutes’, ‘seconds’, ‘ns’ для отображения соответствующих значений и часовой пояс относительно UTC рядом с датой.
—rfc-3339=FMT Вывод даты в формате RFC 3339. FMT по умолчанию содержит ‘date’. Также может содержать ‘seconds’ и ‘ns’ для отображения секунд или наносекунд.
-r FILE —reference=FILE Вывод даты последней модификации указанного файла в формате по умолчанию.
-u —utc Вывод UTC-даты

Аргумент ФОРМАТ отвечает за форматирование вывода даты. Для его указания необходимо поставить знак «+» и написать нужную маску. Наиболее популярные форматы:

Формат Значение
%% Знак процента
%a День недели текущей локали в короткой форме («Чтв»)
%A День недели текущей локали в длинной форме («Четверг»)
%b Месяц года текущей локали в короткой форме в родительном падеже («янв»)
%B Месяц года текущей локали в длинной форме в родительном падеже («января»)
%c Дата и время текущей локали без указания часового пояса
Первые две цифры текущего года
%d Числовой день месяца с ведущим нулём
%D Дата в формате %m/%d/%y
%e День месяца; аналог %_d
%F Дата в формате %Y-%m-%d
%h Аналог %b
%H Часы (00..23)
%I Часы (01..12)
%j День года (001..366)
%m Месяц (01..12)
%M Минуты (00..59)
%n Новая строка
%q Квартал года
%S Секунды (00..59)
%t Знак табуляции
%T Время в формате %H:%M:%S
%u Числовой день недели; 1 — понедельник
%x Дата в локальном формате
%X Время в локальном формате
%Z Аббревиатура временной зоны

Примеры использования date

Введем команду без параметров.

Будет отображена текущая дата и время в соответствии с настройками локали системы.

Команда date без параметров по умолчанию применяет маску %a %b %d %X %Z. Поскольку все форматы должны быть переданы как один параметр (из-за принципа обработки данных командным интерпретатором Bash), пробелы между ними необходимо экранировать обратным слэшем (\) или взять в кавычки.

Особое внимание следует уделить параметру -d (—date). Его функциональность не слишком очевидна, но при этом наиболее обширна.

Пример 1. Вычисление даты по числу секунд, прошедших с 1 января 1970 года.

Пример 2. Вычисление даты и времени следующего понедельника при указании часового пояса Нью-Йорка в 03:00.

date —date=’TZ=»America/New_York» 03:00 next mon’

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

Пример 3. Если текущий день месяца — последний, сформировать отчет о занятости дискового пространства корневого и домашнего каталога в файл report.

#!/bin/bash
if [[ $(date —date=’next day’ +%d) = ’01’ ]]; then
df -h / /home > report

Такой скрипт можно использовать для автоматизации работы с помощью демона crontab или anacron.

Выводы

Команда date Linux является эффективным инструментом работы с датой и временем, с широкой возможностью их расчёта для прошедших или будущих показателей. Также она применяется в написании сценариев в командном интерпретаторе Bash.

Источник

Linux Set Date and Time From a Command Prompt

H ow can I set the system date and time from the command prompt (bash shell)? I don’t have GUI installed and I am login over ssh session. How can I set date under Linux operating systems?

Use the date command to display the current date and time or set the system date / time over ssh session. You can also run the date command from X terminal as root user.

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements None
Est. reading time 2m

This is useful if the Linux server time and/or date is wrong, and you need to set it to new values from the shell prompt.

You must login as root user to use date command.

Linux Display Current Date and Time

Just type the date command:
$ date
Sample outputs:

Linux Display The Hardware Clock (RTC)

Type the following hwclock command to read the Hardware Clock and display the time on screen:
# hwclock -r
OR
# hwclock —show
$ sudo hwclock —show —verbose

OR show it in Coordinated Universal time (UTC):
# hwclock —show —utc
Sample outputs:

Linux Set Date Command Example

Use the following syntax to set new data and time:
date —set=»STRING»
For example, set new data to 2 Oct 2006 18:00:00, type the following command as root user:
# date -s «2 OCT 2006 18:00:00»
OR
# date —set=»2 OCT 2006 18:00:00″
You can also simplify format using following syntax:
# date +%Y%m%d -s «20081128»

Linux Set Time Examples

To set time use the following syntax:
# date +%T -s «10:13:13»
Where,

Use %p locale’s equivalent of either AM or PM, enter:
# date +%T%p -s «6:10:30AM»
# date +%T%p -s «12:10:30PM»

How do I set the Hardware Clock to the current System Time?

Use the following syntax:
# hwclock —systohc
OR
# hwclock -w

A note about systemd based Linux system

With systemd based system you need to use the timedatectl command to set or view the current date and time. Most modern distro such as RHEL/CentOS v.7.x+, Fedora Linux, Debian, Ubuntu, Arch Linux and other systemd based system need to the timedatectl utility. Please note that the above command should work on modern system too.

timedatectl: Display the current date and time

Type the following command:
$ timedatectl

Fig.01: Systemd Linux timedatecetl command to display the current date and time

How do I change the current date using the timedatectl command?

To change the current date, type the following command as root user:
# timedatectl set-time YYYY-MM-DD
OR
$ sudo timedatectl set-time YYYY-MM-DD
For example set the current date to 2015-12-01 (1st, Dec, 2015):
# timedatectl set-time ‘2015-12-01’
# timedatectl
Sample outputs:

To change both the date and time, use the following syntax:
# timedatectl set-time YYYY-MM-DD HH:MM:SS
Where,

  1. HH : An hour.
  2. MM : A minute.
  3. SS : A second, all typed in two-digit form.
  4. YYYY: A four-digit year.
  5. MM : A two-digit month.
  6. DD: A two-digit day of the month.

For example, set the date ’23rd Nov 2015′ and time to ‘8:10:40 am’, enter:
# timedatectl set-time ‘2015-11-23 08:10:40’
# date

  • 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 set the current time only?

The syntax is:
# timedatectl set-time HH:MM:SS
# timedatectl set-time ’10:42:43′
# date
Sample outputs:

How do I set the time zone using timedatectl command?

To see list all available time zones, enter:
$ timedatectl list-timezones
$ timedatectl list-timezones | more
$ timedatectl list-timezones | grep -i asia
$ timedatectl list-timezones | grep America/New
To set the time zone to ‘Asia/Kolkata’, enter:
# timedatectl set-timezone ‘Asia/Kolkata’
Verify it:
# timedatectl

How do I synchronizing the system clock with a remote server using NTP?

Simply type the following command:
# timedatectl set-ntp yes
Verify it:
$ timedatectl
Sample outputs:

Conclusion

Linux users can use date command to print or set the system date and time. Systemd based Linux users can use timedatectl to control the system time and date.

  • You can also set new timzone using this mini-howto.
  • Man pages – timedatectl(8)

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

Источник

Читайте также:  Узнать версию snmp windows
Оцените статью