Linux date formatting example

Содержание
  1. Команда Date в Linux с примерами
  2. Linux Date Command with Examples
  3. В этом руководстве мы рассмотрим основы date команды.
  4. Использование Date
  5. Параметры форматирования даты
  6. Пользовательское форматирование даты
  7. Переопределить часовой пояс
  8. Конвертер эпох
  9. Использование date с другими командами
  10. Показать время последнего изменения файла
  11. Установите системное время и дату
  12. Вывод
  13. ⏲️ 8 примеров команды date на Linux
  14. Базовый синтаксиc
  15. 1) Команда date без параметров
  16. 2) Отображение даты и времени в формате UTC
  17. 3) Отображение определенной даты в строковом формате
  18. 4) Использование команды date, чтобы проверить прошлые даты
  19. 5) Использование команды date, чтобы проверить будущие даты
  20. 6) Параметры форматирования даты
  21. 7) Как установить дату и время
  22. 8) Использование команды Date в переменной
  23. Заключение
  24. Linux date command
  25. Syntax
  26. Options
  27. Date format
  28. Examples
  29. Related commands
  30. How To Format Date For Display or Use In a Shell Script
  31. Linux Syntax To Format Date For Display On Screen
  32. Task: Display date in mm-dd-yy format
  33. Task: Display time only
  34. How do I save time/date format to the shell variable?
  35. A sample shell script
  36. A complete list of FORMAT control characters supported by the GNU/date command
  37. A complete list of FORMAT control characters supported by the BSD/date command
  38. A sample date session

Команда 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 отображает или устанавливает системную дату и время.

Источник

⏲️ 8 примеров команды date на Linux

Базовый синтаксиc

Базовый синтаксис команды date представлен ниже:

1) Команда date без параметров

2) Отображение даты и времени в формате UTC

Чтобы отобразить время в формате UTC (всемирное координированное время), ранее называвшееся GMT (среднее время по Гринвичу), добавьте параметр -u.

3) Отображение определенной даты в строковом формате

4) Использование команды date, чтобы проверить прошлые даты

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

Например, чтобы проверить дату 9 дней назад, выполните команду.

Читайте также:  Лучший плеер для windows x64

5) Использование команды date, чтобы проверить будущие даты

Так же, как вы можете проверять прошлые даты, команда date также позволяет отображать будущие даты.

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

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

  • %D – Отображение даты в формате мм / дд / гг
  • %Y – Год (например, 2021 г.)
  • %m – Месяц (01-12)
  • %B – Название месяца в формате полной строки (например, February)
  • %b –Название месяца в сокращенном строковом формате (например, Feb).
  • %d – День месяца (например, 01)
  • %j – День года (001-366)
  • %u – День недели (1-7)
  • %A –День недели в формате полной строки (например, Friday)
  • %a – День недели в сокращенном формате (например, Fri)
  • %H – Час (00-23)
  • %I – Час (01-12)
  • %M – Mинута (00-59)
  • %S – Секунда (00-60)

Синтаксис использования опции date довольно прост:

Чтобы вывести день недели, месяц, год и текущее время:

7) Как установить дату и время

Команда date также позволяет вам установить дату и время.

Например, чтобы установить дату и время на 25 июня 2021 года в 11:15, выполните команду:

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

Лучший способ добиться этого – использовать утилиту chrony, которая является заменой устаревшего демона ntpd.

Фактически, современные системы, такие как CentOS 8/RHEL 8, не поддерживают NTP.

У нас есть подробное руководство о том, как синхронизировать время и дату с помощью chrony.

Если вы хотите изменить часовой пояс, используйте команду timedatectl, пример показан ниже.

8) Использование команды Date в переменной

Заключение

Мы надеемся, что пролили свет на использование команды date на Linux, и надеемся, что вы сможете использовать ее для отображения даты в системе и настройки вывода по своему усмотрению.

Источник

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).
Читайте также:  Файловая система внешних дисков для mac os

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.

Источник

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:

Источник

Читайте также:  Астра линукс системы виртуализации
Оцените статью