Linux date format iso

Команда 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.

Источник

How To Format Date For Display or Use In a Shell Script

H ow do I format the date to display on the screen on for my shell scripts as per my requirements on Linux or Unix like operating systems?

You need to use the standard date command to format date or time in Linux or Unix shell scripts. You can use the same command with the shell script. This page shows how to format date in Linux or Unix-based system.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements date on Linux/Unix
Est. reading time 7 minutes

Linux Syntax To Format Date For Display On Screen

The syntax is as follows for the GNU/date and BSD/date command:
date +FORMAT
date +»%FORMAT»
date +»%FORMAT%FORMAT»
date +»%FORMAT-%FORMAT»
An operand with a leading plus ( + ) sign signals a user-defined format string which specifies the format in which to display the date and time. The following examples are tested on GNU/Linux, Apple OS X Unix, and FreeBSD unix operating system.

Task: Display date in mm-dd-yy format

Open a terminal and type the following date command:
$ date +»%m-%d-%y»
Sample outputs:

To turn on 4 digit year display:
$ date +»%m-%d-%Y»
Just display date as mm/dd/yy format:
$ date +»%D»

Task: Display time only

Type the following command:
$ date +»%T»
Sample outputs:

To display locale’s 12-hour clock time, enter:
$ date +»%r»
Sample outputs:

To display time in HH:MM format, type:
$ date +»%H-%M»
Sample outputs:

How do I save time/date format to the shell variable?

Simply type the following command at the shell prompt to get the current date in MM-DD-YYYY format:
$ NOW=$(date +»%m-%d-%Y»)
To display a variable use the following simple commands to output on screen under Linux and UNIX using the printf command/echo command:
$ echo «$NOW»
printf «%s\n» $NOW

A sample shell script

A complete list of FORMAT control characters supported by the GNU/date command

It can be the combination of any one of the following:

Table 1 – FORMAT controls the output for Linux

%FORMAT String Description
%% a literal %
%a locale’s abbreviated weekday name (e.g., Sun)
%A locale’s full weekday name (e.g., Sunday)
%b locale’s abbreviated month name (e.g., Jan)
%B locale’s full month name (e.g., January)
%c locale’s date and time (e.g., Thu Mar 3 23:05:25 2005)
%C century; like %Y, except omit last two digits (e.g., 21)
%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 ( 0..23)
%l hour ( 1..12)
%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 lower case
%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 timezone (e.g., -0400)
%:z +hh:mm numeric timezone (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)

A complete list of FORMAT control characters supported by the BSD/date command

The following works on Apple macOS/OS X, FreeBSD and *BSD version of the date command:

  • 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

Table 2 – BSD/date command
%FORMAT String Description
%A is replaced by national representation of the full weekday name.
%a is replaced by national representation of the abbreviated weekday name.
%B is replaced by national representation of the full month name.
%b is replaced by national representation of the abbreviated month name.
%C is replaced by (year / 100) as decimal number; single digits are preceded by a zero.
%c is replaced by national representation of time and date.
%D is equivalent to “%m/%d/%y”.
%d is replaced by the day of the month as a decimal number (01-31).
%E* %O* POSIX locale extensions. The sequences %Ec %EC %Ex %EX %Ey %EY %Od %Oe %OH %OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy are supposed to provide alternate representations.
Additionally %OB implemented to represent alternative months names (used standalone, without day mentioned).
%e is replaced by the day of the month as a decimal number (1-31); single digits are preceded by a blank.
%G is replaced by a year as a decimal number with century. This year is the one that contains the greater part of the week (Monday as the first day of the week).
%g is replaced by the same year as in “%G”, but as a decimal number without century (00-99).
%H is replaced by the hour (24-hour clock) as a decimal number (00-23).
%h the same as %b.
%I is replaced by the hour (12-hour clock) as a decimal number (01-12).
%j is replaced by the day of the year as a decimal number (001-366).
%k is replaced by the hour (24-hour clock) as a decimal number (0-23); single digits are preceded by a blank.
%l is replaced by the hour (12-hour clock) as a decimal number (1-12); single digits are preceded by a blank.
%M is replaced by the minute as a decimal number (00-59).
%m is replaced by the month as a decimal number (01-12).
%n is replaced by a newline.
%O* the same as %E*.
%p is replaced by national representation of either “ante meridiem” (a.m.) or “post meridiem” (p.m.) as appropriate.
%R is equivalent to “%H:%M”.
%r is equivalent to “%I:%M:%S %p”.
%S is replaced by the second as a decimal number (00-60).
%s is replaced by the number of seconds since the Epoch, UTC (see mktime(3)).
%T is equivalent to “%H:%M:%S”.
%t is replaced by a tab.
%U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number (00-53).
%u is replaced by the weekday (Monday as the first day of the week) as a decimal number (1-7).
%V is replaced by the week number of the year (Monday as the first day of the week) as a decimal number (01-53). If the week containing January 1 has four or more days in the new year, then it is week 1; otherwise it is the last week of the previous year, and the next week is week 1.
%v is equivalent to “%e-%b-%Y”.
%W is replaced by the week number of the year (Monday as the first day of the week) as a decimal number (00-53).
%w is replaced by the weekday (Sunday as the first day of the week) as a decimal number (0-6).
%X is replaced by national representation of the time.
%x is replaced by national representation of the date.
%Y is replaced by the year with century as a decimal number.
%y is replaced by the year without century as a decimal number (00-99).
%Z is replaced by the time zone name.
%z is replaced by the time zone offset from UTC; a leading plus sign stands for east of UTC, a minus sign for west of UTC, hours and minutes follow with two digits each and no delimiter between them (common form for RFC 822 date headers).
%+ is replaced by national representation of the date and time (the format is similar to that produced by date(1)).
%-* GNU libc extension. Do not do any padding when performing numerical outputs.
%_* GNU libc extension. Explicitly specify space for padding.
%0* GNU libc extension. Explicitly specify zero for padding.
%% is replaced by %.

A sample date session

I am running commands on macOS/OS X and FreeBSD:

Источник

Читайте также:  Как включить значок центра уведомлений windows 10
Оцените статью