Date cmd on 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

Источник

Linux date command

On Unix-like operating systems, the date command is used to print out, or change the value of, the system’s time and date information.

This page covers the GNU/Linux version of date.

Syntax

Options

-d, —date=STRING Display time described by string STRING, instead of the default, which is ‘now‘.
-f, —file=DATEFILE Like —date, but processed once for each line of file DATEFILE.
-I[TIMESPEC],
—iso-8601[=TIMESPEC]
Output date/time in ISO 8601 format. For values of TIMESPEC, use ‘date‘ for date only (the default), ‘hours‘, ‘minutes‘, ‘seconds‘, or ‘ns‘ for date and time to the indicated precision.
-r, —reference=FILE Display the last modification time of file FILE.
-R, —rfc-2822 Output date and time in RFC 2822 format. Example: Mon, 07 Aug 2006 12:34:56 -0600
—rfc-3339=TIMESPEC Output date and time in RFC 3339 format. TIMESPEC can be set to ‘date‘, ‘seconds‘, or ‘ns‘ for date and time to the indicated precision. Date and time components are separated by a single space, for example: 2006-08-07 12:34:56-06:00
-s, —set=STRING Set time described by string STRING.
-u, —utc, —universal Print or set Coordinated Universal Time.
—help Display a help message and exit.
—version Display version information and exit.

Date format

FORMAT is a sequence of characters which specifies how output appears. It comprises some combination of the following sequences:

%% A literal percent sign («%«).
%a The abbreviated weekday name (e.g., Sun).
%A The full weekday name (e.g., Sunday).
%b The abbreviated month name (e.g., Jan).
%B Locale’s full month name (e.g., January).
%c The date and time (e.g., Thu Mar 3 23:05:25 2005).
%C The current century; like %Y, except omit last two digits (e.g., 20).
%d Day of month (e.g., 01).
%D Date; same as %m/%d/%y.
%e Day of month, space padded; same as %_d.
%F Full date; same as %Y-%m-%d.
%g Last two digits of year of ISO week number (see %G).
%G Year of ISO week number (see %V); normally useful only with %V.
%h Same as %b.
%H Hour (00..23).
%I Hour (01..12).
%j Day of year (001..366).
%k Hour, space padded ( 0..23); same as %_H.
%l Hour, space padded ( 1..12); same as %_I.
%m Month (01..12).
%M Minute (00..59).
%n A newline.
%N Nanoseconds (000000000..999999999).
%p Locale’s equivalent of either AM or PM; blank if not known.
%P Like %p, but lowercase.
%r Locale’s 12-hour clock time (e.g., 11:11:04 PM).
%R 24-hour hour and minute; same as %H:%M.
%s Seconds since 1970-01-01 00:00:00 UTC.
%S Second (00..60).
%t A tab.
%T Time; same as %H:%M:%S.
%u Day of week (1..7); 1 is Monday.
%U Week number of year, with Sunday as first day of week (00..53).
%V ISO week number, with Monday as first day of week (01..53).
%w Day of week (0..6); 0 is Sunday.
%W Week number of year, with Monday as first day of week (00..53).
%x Locale’s date representation (e.g., 12/31/99).
%X Locale’s time representation (e.g., 23:13:48).
%y Last two digits of year (00..99).
%Y Year.
%z +hhmm numeric time zone (e.g., -0400).
%:z +hh:mm numeric time zone (e.g., -04:00).
%::z +hh:mm:ss numeric time zone (e.g., -04:00:00).
%. z Numeric time zone with «:» to necessary precision (e.g., -04, +05:30).
%Z Alphabetic time zone abbreviation (e.g., EDT).

By default, date pads numeric fields with zeroes. The following optional flags may follow ‘%‘:

(Hyphen) do not pad the field.
_ Pad with spaces.
0 Pad with zeros.
^ Use uppercase if possible.
# Use opposite case if possible.

After any flags comes an optional field width, as a decimal number; then an optional modifier, which is either E to use the locale’s alternate representations if available, or O to use the locale’s alternate numeric symbols if available.

Examples

Running date with no options outputs the system date and time, as in the following output:

Set the system date and time to November 20, 2003, 12:48 PM.

Outputs the date and time in the following format:

In bash, this command generates a directory listing with ls, and redirect the output to a file which includes the current day, month, and year in the file name. It does this using bash command substitution, running the date command in a subshell and inserting that output into the original command.

time — Report how long it takes for a command to execute.

Источник

Команда Date в Linux с примерами

Linux Date Command with Examples

В этом руководстве мы рассмотрим основы date команды.

Команда date отображает или устанавливает системную дату. Чаще всего он используется для печати даты и времени в разных форматах и ​​для расчета будущих и прошлых дат.

Использование Date

Синтаксис date команды следующий:

Выходные данные включают день недели, месяц, день месяца, время, часовой пояс и год:

Параметры форматирования даты

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

Символ %Y будет заменен на год, %m месяц и %d день месяца:

Вот еще один пример:

Ниже приведен небольшой список некоторых наиболее распространенных символов форматирования:

  • %a — Сокращенное название дня недели (например, понедельник)
  • %A — Сокращенное полное название дня недели (например, понедельник)
  • %b — Сокращенное название месяца (например, январь).
  • %B — сокращенное длинное название месяца (например, январь)
  • %d — день месяца (например, 01)
  • %H — час (00..23)
  • %I — час (01.12.12)
  • %j — День года (001..366)
  • %m — Месяц (01.12.12)
  • %M — Минута (00..59)
  • %S — Второй (00 .. 60)
  • %u — день недели (1..7)
  • %Y — Полный год (например, 2019)

Чтобы получить полный список всех параметров форматирования, запустите date —help или man date в своем терминале.

Пользовательское форматирование даты

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

Использование пользовательского форматирования:

Строка даты принимает значения, такие как «завтра», «пятница», «последняя пятница», «следующая пятница», «следующий месяц», «следующая неделя» .. и т. Д.

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

Переопределить часовой пояс

Команда date возвращает дату в системном часовом поясе по умолчанию . Чтобы использовать другой часовой пояс, установите переменную среды TZ в желаемый часовой пояс.

Например, чтобы показать время в Мельбурне, введите:

Чтобы получить список всех доступных часовых поясов , вы можете либо перечислить файлы в /usr/share/zoneinfo каталоге, либо использовать timedatectl list-timezones команду.

Конвертер эпох

date Команда может быть использована в качестве преобразователя Epoch. Время, или метки времени Unix, — это количество секунд, прошедших с 1 января 1970 года в 00:00:00 UTC.

Чтобы напечатать количество секунд от эпохи до текущего дня, вызовите date с %s контролем формата:

Чтобы преобразовать секунды с начала эпохи в дату, установите секунды в виде строки даты с префиксом @ :

Использование date с другими командами

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

Команда ниже создаст файл резервной копии Mysql в следующем формате database_name-20190601.sql

Вы также можете использовать date команду в своих сценариях оболочки. В приведенном ниже примере мы присваиваем выход date к date_now переменной:

Показать время последнего изменения файла

Команда date с -r параметром показывает время последнего изменения файла. Например:

Если вы хотите изменить временную метку файла, используйте touch команду .

Установите системное время и дату

Установка системного времени и даты вручную с помощью этой date команды не рекомендуется, поскольку в большинстве дистрибутивов Linux системные часы синхронизируются с ntp помощью systemd-timesyncd служб или .

Однако, если вы хотите установить системные часы вручную, вы можете использовать эту —set= опцию. Например, если вы хотите установить дату и время 17:30, 01 июня 2019 г., введите:

Вывод

Команда Linux date отображает или устанавливает системную дату и время.

Источник

Читайте также:  Pure music для windows
Оцените статью